Problem
I have some dynamically generated HTML (using JavaScript) that contains a form with some radio buttons in it. I added event listeners (using "change"
) to all of the radio buttons to call a function whenever their value is changed. I am already aware that this event only triggers when a button's "checked
" value goes from false
to true
, and not the other way around.
To simplify my code, I've wrapped the label
tags around the input
tags to avoid having to generate a bunch of unique id's for my radio buttons. However, when the label
tags are wrapped around the radio inputs rather than sitting in the same scope as the radio inputs, the "change" event listener does not respond, even when clicking directly on the button itself.
Examples
I put together a jsfiddle example to show what I'm talking about. JS Fiddle Example
The first group (that doesn't work) is generated this way:
for (var i = 0; i < 3; i++)
{
var label = document.createElement("label");
var radio = document.createElement("input");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "group1");
radio.addEventListener("change", function()
{
alert("group1 changed!")
}, false);
label.appendChild(radio);
label.innerHTML += "Radio " + (i + 1);
var br = document.createElement("br");
g1.appendChild(label);
g1.appendChild(br);
}
And the second group (that does work) is generated this way:
for (var i = 0; i < 3; i++)
{
var radio = document.createElement("input");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "group2");
radio.setAttribute("id", "g2r" + i);
radio.addEventListener("change", function()
{
alert("group2 changed!")
}, false);
var label = document.createElement("label");
label.setAttribute("for", "g2r" + i);
label.innerHTML = "Radio " + (i + 1);
var br = document.createElement("br");
g2.appendChild(radio);
g2.appendChild(label);
g2.appendChild(br);
}
Question
Is this an known bug or something? And is there some kind of workaround? I'd like to keep the wrapped labels because it's easier to generate, and I think it's cleaner, but not at the expense of functionality, obviously.
Thank you!