JQuery change method in vanilla javascript?

I wrote a small jQuery code snippet below that uses the change method. I just found out that jQuery is no longer used in the project, so I need to rewrite the change method in Vanilla JS. Just looking for some help on how I can do this. Here is the code, it pulls the value of one input and enters it into another.

(function(){ $('#Email').change(function() { $('#UserName').val($(this).val()); }); })(); 
+11
javascript jquery
source share
3 answers

Browsers depend on how events should be attached. You might 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); } 

In the following example, I assume that your IIFE really should have been a DOM ready event. The IIFE in your code doesn't seem to actually serve any purpose. So...

There are two events in your code: an event ready for the DOM ("DOMContentLoaded"), and an event to change the select element ("onchange"). Using the above helper, your jQuery syntax is converted to:

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

Here is 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" /> 
+10
source share

If you do not need to support the old IE, you can use querySelector + addEventListener :

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

Visually, it looks the same as with jQuery .on('change', fn) (which calls .change() ), just more verbose.

+17
source share

There is a change event :

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

JS:

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

All Articles