Reputation: 9
I am new to Javascript. I have a question, how can I automatically add text next to a radio button using javascript. I have the following code:
for (var index=0; index<4; index++)
{
var text = "Hello" + index;
var name = 'RadioButton' + (index+1);
var radioBut = document.createElement('input');
radioBut.setAttribute('type', 'radio');
radioBut.setAttribute('name', name);
document.body.appendChild(radioBut);
var newdiv = document.createElement('div');
var divIdName = 'my'+index+'Div';
newdiv.setAttribute('id',divIdName);
document.body.appendChild(newdiv);
newdiv.innerHTML = text;
}
It prints the radio buttons but the text is obviously printed below. What must I do to get the following format: RadioButton + Text?
Upvotes: 1
Views: 2447
Reputation: 193261
Div is block level element so it's gets rendered on the new line. Use some inline element like span or label instead:
for (var index = 0; index < 4; index++) {
var text = "Hello" + index;
var name = 'RadioButton'; // + (index + 1);
var id = 'my' + index + 'Div';
var row = document.createElement('div');
document.body.appendChild(row);
var radioBut = document.createElement('input');
radioBut.setAttribute('type', 'radio');
radioBut.setAttribute('name', name);
radioBut.setAttribute('id', id);
row.appendChild(radioBut);
var label = document.createElement('label');
label.setAttribute('for', id);
label.innerHTML = text;
row.appendChild(label);
}
With label
you can specify for
attribute which would point to corresponding input element, this is good for UX. Also note, that it makes sense to give the same name for radio buttons.
Upvotes: 2