Reputation: 448
I am trying to create a dynamic form so on click of a button I call a Javascript function. here is the function:
function addradiobutton(type){
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
counter=counter+1;
}
This code adds a radio button and its tag is like this
<input type="radio" name="radio" value="radio">
But I want to make this code like this.
<input type="radio" name="radio" value="radio">WATER</input>
I dont mind about closing input tag but I want to get the value 'Water' their at the end of the code.
Water is just taken for example its value would be dynamic as well.
What should I do ?
Upvotes: 0
Views: 10607
Reputation: 833
One solution that I would use is create it not like that but more: (using jQuery for simplicity with syntax)
<div id="buttons">
</div>
<scrpit>
var temp;
temp = '<label><input type="radio" name="radio" value="radio" />WATER</label>';
temp + '<label><input type="radio" name="radio" value="radio" />WATER1</label>';
$('#buttons').html(temp);
</script>
Untested but the logic should work, i will try update for errors.
if you want x amount you could put it in a function with a for loop looping to x and iterating those out. Example:
<script>
function addButtons(number){
for(var i=0;i<number;i++){
// do the string appending here
}
}
</script>
Upvotes: 0
Reputation: 19591
Try this
<script type="text/javascript">
var counter = 0;
function addradiobutton(type, text) {
var label = document.createElement("label");
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
label.appendChild(element);
label.innerHTML += text;
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(label);
counter = counter + 1;
}
addradiobutton("radio", "Water");
</script>
Upvotes: 6
Reputation: 943579
<input type="radio" name="radio" value="radio">WATER</input>
… is invalid HTML. The way to express what you are trying to express is:
<label><input type="radio" name="radio" value="radio">WATER</label>
You just need to create a label element, and then appendChild
both the input element and the text node.
var label, input;
label = document.createElement('label');
input = document.createElement('input');
// Set type, name, value, etc on input
label.appendChild(input);
label.appendChild('Water');
foo.appendChild(label);
Upvotes: 2