Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
  });

})();
like image 486
Stavros_S Avatar asked Jun 11 '14 21:06

Stavros_S


2 Answers

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.

like image 97
RaphaelDDL Avatar answered Sep 22 '22 09:09

RaphaelDDL


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" />
like image 23
Cᴏʀʏ Avatar answered Sep 20 '22 09:09

Cᴏʀʏ