Reputation: 389
I want to add an event handler for input text controls. The controls is generated dynamically. My code is like:
JavaScript:
var settings_check = new Array("checkVMName()","checkDiskMB()","checkMemMB()","checkEsx()","checkDatastore()");
...
_inputbox = document.createElement("input");
_inputbox.type = "text";
_inputbox.id = settings[zindex];
_inputbox.onblur = settings_check[zindex];
_hint = document.createElement("hint");
_hint.id = settings[zindex] + "_Label2";
_hint.innerText = settings_hint[zindex];
mycurrent_cel2.appendChild(_inputbox);
mycurrent_cel2.appendChild(_hint);
But this way doesn't work. I checked the HTML with Firebug, and no "onblur" attribute for the input text control at all.
HTML
<tr> <td>....</td> <td><input type="text" id="Datastore"> <hint id="Datastore_Label2">start with /</hint> </td> </tr>
I also tried other ways to set event handler like
_inputbox.onblur = function(){alert("test");};
or
_inputbox.setAttribute("onblur",func);
Neither works. :(
If I manually add onblur=function(){...} for the input text control in the HTML with Firebug and execute, the onblur does work. So the question is: how can I set event handler for a control in JavaScript? Is there anything wrong in my code? Thanks.
Upvotes: 0
Views: 437
Reputation: 163288
You are creating an array of strings with function invocations in them, this is completely incorrect.
You need to assign references to the functions that you wish to be invoked when the event fires. You'd do this by simply storing the names of the functions (without the ()
or quotes) in your array, and it should work (the functions must be previously defined in the current scope as well):
var settings_check = [checkVMName, checkDiskMB, checkMemMB, checkEsx, checkDatastore];
So, in essence, settings_check
is simply an array of function references.
See this jsFiddle example illustrating this concept.
Upvotes: 2