onclick handler not firing for checkbox created with document.createElement
I am going insane trying to figure out why this is not working. I am creating a checkbox dynamically with JS to enable/disable a text field (also created dynamically).
Code is pretty simple:
var text = $(document.createElement("input"));
text.type = "text";
container.appendChild(text);
...
var check = $(document.createElement("input"));
check.type = "checkbox";
check.onclick = function(event) {
if (this.checked) text.enable();
else text.disable();
};
container.appendChild(check);
I've tried putting the event handler after container.appendChild(check);
, but that yields the same result.
There are no JS errors, and results are the same in Chrome, FF3.6, and IE7.
Can anyone explain why this isn't working? Any fixes would be appreciated.
Strangely (because t开发者_开发技巧heoretically it should be the same as above), adding the following (after container.appendChild(check);
) works (checkbox is first on page):
$$("input[type=checkbox]")[0].onclick = function(event) {
if (this.checked) text.enable();
else text.disable();
};
I don't really like this, as it seems "dirty", and the checkbox may not be the first on the page later on...
BTW, $ and $$ are from Prototype.
Thanks in advance for any help.
I figured out what was causing the problem...
After all of this code, I was adding some text by appending to innerHTML of container
. For some reason, this threw off all of the event handlers for that container.
Using container.appendChild(document.createTextNode("..."));
fixed the problem.
Hope this helps anyone else who might be having this sort of problem...
Are you sure you don't have any errors?
craeteElement
is misspelled in the first line. After fixing that, it all works on my machine with 1.6.1 and 1.7RC1.
http://jsfiddle.net/4XWP3/
Do you need to use the $(...)
wrappers? Why not:
var text = document.createElement("input");
text.type = "text";
container.appendChild(text);
...
var check = document.createElement("input");
check.type = "checkbox";
check.onclick = function(event) {
if (check.checked) text.enable();
else text.disable();
};
container.appendChild(check);
Also, note that I changed if (this.checked)
to if (check.checked)
since this
can get crazy in JS.
Works for me. Prototype is doing nothing for you here, so I'd suggest dropping it. The following works and simplifies things:
var text = document.createElement("input");
text.type = "text";
container.appendChild(text);
...
var check = document.createElement("input");
check.type = "checkbox";
check.onclick = function(event) {
text.disabled = !this.checked;
};
container.appendChild(check);
精彩评论