简体   繁体   中英

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM