javascript - how to copy another elements onclick function -


i have been able elements onclick function doing this:

document.getelementbyid(this.options[this.selectedindex].text).getattribute('onclick') 

this gives me exact text want put different elements onchange event, thought this:

<select onchange="document.getelementbyid(this.options[this.selectedindex].text).getattribute('onclick')"> 

this not work though. have ideas, stumped! in advance!

you can't dump function attribute that. recommend start writing unobtrusive javascript.

html

<select id="myselect">     <!-- snip --> </select> 

javascript

var select = document.getelementbyid('myselect'); select.onchange = function () {     var id = this.options[this.selectedindex].text,         clickhandler = document.getelementbyid(id).onclick;     clickhandler.apply(this); }; 

demo →


edit re: op's comment

"is there easy way apply selects on page?"

of course there is! need careful not creating functions in loop (it won't work).

var selects = document.getelementsbytagname('select'),     numselects = selects.length,     i;  function setclickhandler(element) {     element.onchange = function () {         var id = this.options[this.selectedindex].text,             clickhandler = document.getelementbyid(id).onclick;         clickhandler.apply(this);     } }  (i=0; i<numselects; i++) {     setclickhandler(selects[i]); } 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -