Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a second onChange event?

Hi I found this script online that adds an onChange event to an element and I would like to now add a second onChange event to the same element. Heres the script:

document.getElementById('piname').onchange =
function() {
    removeChildren({
        parentId: 'account_table',
        childName: 'extraaccount'
    });
}

And the onChange event i want to add is:

showAccount(this.value)
like image 856
Jonah Katz Avatar asked Jul 26 '11 14:07

Jonah Katz


People also ask

Can we use two Onchange event?

You can only assign a handler to onChange once. When you use multiple assignments like that, the second one will overwrite the first one.

What is the difference between Onchange and Oninput?

The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed.

Can you add Onchange to div?

No; the onchange attribute is only applicable to form field elements ( input , select , textarea , etc). Thanks for your answer. How do I do it?


2 Answers

Use addEventListener() (and attachEvent as a fallback, if needed).
Example:

document.getElementById('piname').addEventListener("change", function(e){
  e = e || event;
  showAccount(e.target.value);
}, false);

Example, with fallback:

var element = document.getElementById('piname');
if(element.addEventListener){
  element.addEventListener("change", function(e){
    e = e || event;
    showAccount(e.target.value);
  }, false);
}
else if(element.attachEvent){
  element.attachEvent("onchange", function(e){
    e = e || event;
    showAccount(e.target.value);
  });
}
like image 148
Digital Plane Avatar answered Oct 20 '22 09:10

Digital Plane


The simplest way is to cache the old function and call it from the new one:

var el = document.getElementById('piname'),
    old = el.onchange;

el.onchange = function () {
    old.call(el);
    showAccount(this.value);
}

Other than that, you could use addEventListener (W3C standards) and attachEvent (IE8 and lower):

var el = document.getElementById('piname'),
    fn = function (e) {
         e = e || window.event;
         showAccount((e.target || e.srcElement).value); 
    };

if ("addEventListener" in el) {
    el.addEventListener("change", fn, false);
}
else {
    el.attachEvent("onchange", fn);
}

Those methods allow you to attach as many handlers to events as you like.

like image 31
Andy E Avatar answered Oct 20 '22 09:10

Andy E