Stavros_S
Stavros_S

Reputation: 2235

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

})();

Upvotes: 24

Views: 39831

Answers (3)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107536

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" />

Upvotes: 15

RaphaelDDL
RaphaelDDL

Reputation: 4480

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.

Upvotes: 44

tymeJV
tymeJV

Reputation: 104785

There is the change event:

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

JS:

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

Upvotes: 2

Related Questions