Reputation: 271
Let me start off by saying my JavaScript skills are lacking, to say the least. I have been having a problem with the following function:
function setClickHandler(element) {
element.onchange = function () {
var id = this.options[this.selectedIndex].value;
if(document.getElementById(id) !== null){
clickHandler = document.getElementById(id).onclick;
} else {
clickHandler ="runMe('" + this.id + "','" + id + "','','null')"; }
clickHandler.apply(this);
}
}
Basically what it does is if a element exists with the "id" then use that elements onclick
function and if it doesn't exist then create the one within the function. Then apply this onclick
function to the element.
Everything works except if the "id" does not exist and it goes into the else statement where the clickHandler
has to be created. I cannot figure out why this won't work. I did notice when I logged it if clickHandler
was taken from another existing id then clickHandler
output something like (onclick).event
where if it went into the else statement it output runMe('24','54','','null')
.
I hope I am explaining this well enough. Any help would be greatly appreciated.
Upvotes: 1
Views: 1043
Reputation: 11238
you're creating a string in the else case, which you can't call as a function. try this
if (document.getElementById(id) !== null) {
clickHandler = document.getElementById(id).onclick;
clickHandler.apply(this);
}
else {
// clickHandler = "runMe('" + this.id + "','" + id + "','','null')";
var runMeArgs = [this.id, id, '', 'null'];
runMe.apply(this, runMeArgs);
}
Upvotes: 2
Reputation: 29411
In one case you're setting clickHandler
to a function, in the other case you're setting it to a string?
if (...) {
...
} else {
var me = this;
clickHandler = function() {
runMe(me.id, id, '', null);
}
}
...
Possibly.
Upvotes: 1