So I am trying to make a dynamic quiz and am struggling with adding text to my radio inputs. I use a for loop to make several radio inputs. I would like the text to be on the same line as each radio choice, but I cannot accomplish this.
When I use append()
it creates a new line then adds the text.
for (j = 0; j < 5; j++) {
$('#target').append('<input type="radio" name="radioName"/>')
$('#target').append('<p>My text here</p>');
When I use the label for
html attribute, it adds the text at the end of all the radios.
for (j = 0; j < 5; j++) {
$('#target').append('<input type="radio" name="radioName"/>').after("<label for='radio'>text here</label>");
Here is my jsFiddle showing the example: http://jsfiddle.net/tCkuF/2/
Ideally I would like to add a variable that represents an object as the text so it changes automatically as the quiz is taken.
It is recommended to use a list element in such cases
<div id="container">
<div id="question"></div>
<div id="target">
<ul id="options">
</ul>
</div>
</div>
Also give styles
#options{
list-style:none;
list-style-type:none;
}
Then add li
element. Give proper id
for using for
attribute
var $li = $("<li>").appendTo("#options");
$li.append('<input id="option' + (j+1) + '" type="radio" name="question' + i + '" value="' + allQuestions[i].correctAnswer + '"/>');
$li.append("<label for='option" + (j+1) + "'>test: label for adds all to the end </label>");
demo : http://jsfiddle.net/tCkuF/6/