Reputation: 6146
Trying to create a basic quiz in javaScript. My code below seems to only output the radio button and not the accompanying labels. Why is this? Heres the full fiddle. Thanks
while(i<length){
var radioBtn = document.createElement("input");
var label = document.createElement("label");
radioBtn.setAttribute('type','radio');
radioBtn.id = i;
label.appendChild(document.createTextNode(data[0].choices[i]));
radioBtn.appendChild(label);
form.appendChild(radioBtn);
i++
}
Upvotes: 0
Views: 60
Reputation: 29285
while(i<length){
var radioBtn = document.createElement("input");
var label = document.createElement("label");
radioBtn.setAttribute('type','radio');
radioBtn.id = i;
label.appendChild(radioBtn); // Append radio button to the label
label.appendChild(document.createTextNode(data[0].choices[i])); // Add a text
form.appendChild(label); // Append to the form
i++;
}
OR alternatively append the label
as the sibling for the radio button and use the for
property of label
element. By this way location of label
relative to the radio button is not matter.
label.setAttribute('for', radioBtn.id);
Upvotes: 0
Reputation: 636
change radioBtn.appendChild(label); to form.appendChild(label);
while(i<length){
var radioBtn = document.createElement("input");
var label = document.createElement("label");
radioBtn.setAttribute('type','radio');
radioBtn.id = i;
label.appendChild(document.createTextNode(data[0].choices[i]));
form.appendChild(label);
form.appendChild(radioBtn);
i++
}
Upvotes: 0
Reputation: 964
You're appending a <label>
to the <input>
and it should be the other way around. Here's an updated plunkr:
Upvotes: 0
Reputation: 944170
You're trying to put the label inside the input. Inputs cannot have child nodes.
You want to put the input inside the label.
This is what you should aim for:
<label>
<input type="radio">
Hello
</label>
This is what your code is attempting to do:
<input type="radio">
<label>
Hello
</label>
</input>
Change:
label.appendChild(document.createTextNode(data[0].choices[i]));
radioBtn.appendChild(label);
form.appendChild(radioBtn);
to
label.appendChild(radioBtn);
label.appendChild(document.createTextNode(data[0].choices[i]));
form.appendChild(label);
Upvotes: 3