Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy another elements onclick function

I have been able to successfully get another elements onclick function by doing this:

document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')

This gives me the exact text that I want to put into a different elements onchange event, so I thought I could do this:

<select onchange="document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')">

This does not work though. Does anyone have any ideas, I am stumped?

like image 953
Chad Avatar asked Jun 25 '26 12:06

Chad


1 Answers

You can't just dump a function into an attribute like that. I recommend that you 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 an easy way to apply this to all the selects on the page?"

Of course there is! But you need to be careful about not creating functions in a 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);
    }
}

for (i=0; i<numSelects; i++) {
    setClickHandler(selects[i]);
}
like image 69
Matt Ball Avatar answered Jun 27 '26 01:06

Matt Ball