jQuery change method in vanilla JavaScript?
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" />
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.