简体   繁体   中英

jQuery change method in vanilla JavaScript?

I wrote a little piece of jQuery code below that uses the change method. I just found out jQuery is no longer being used in the project so I need to re-write the change method in Vanilla JS. Just looking for some assistance on how I can do that. Here is the code, it pulls the value of one input and enters it into another.

(function(){

  $('#Email').change(function() {
    $('#UserName').val($(this).val());
  });

})();

If you don't need to support old IEs, you can use querySelector + addEventListener :

document.querySelector('#Email').addEventListener('change',function(){
    document.querySelector('#UserName').value = this.value;
});

Visually it looks just like it would with jQuery's .on('change', fn) (which is what .change() calls), just more verbose.

Browsers vary on how events should be attached. You'd probably want to start with a little helper method:

function addEventHandler(elem, eventType, handler) {
    if (elem.addEventListener)
        elem.addEventListener (eventType, handler, false);
    else if (elem.attachEvent)
        elem.attachEvent ('on' + eventType, handler); 
}

For the following sample, I'm going to assume that your IIFE should have really been a DOM-ready event. The IIFE in your code doesn't seem to really serve any purpose. So...

There are two events from your code, the DOM-ready event ("DOMContentLoaded") and the select element's change event ("onchange"). Taking advantage of the above helper, your jQuery syntax translates to:

addEventHandler(document, 'DOMContentLoaded', function() {
    addEventHandler(document.getElementById('Email'), 'change', function() {
        document.getElementById('UserName').value = this.value;
    });
});

Here's a demo:

  function addEventHandler(elem, eventType, handler) { if (elem.addEventListener) elem.addEventListener (eventType, handler, false); else if (elem.attachEvent) elem.attachEvent ('on' + eventType, handler); } addEventHandler(document, 'DOMContentLoaded', function() { addEventHandler(document.getElementById('Email'), 'change', function() { document.getElementById('UserName').value = this.value; }); }); 
 <select id="Email"> <option value=""></option> <option value="Test 1">Test 1</option> <option value="Test 2">Test 2</option> </select> <input id="UserName" type="text" /> 

There is the change event :

<select id="select"></select>

JS:

document.getElementById("select").onchange = function() { console.log("Changed!"); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM