I'm trying to create 10 radio buttons, labeled 1-10 with a for loop inside of my html and I can't get it to work.
<html>
<body>
<h2 style="text-align:center">
On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?
</h2>
<form id="NPSform"; style= "text-align:center">
<script>
for (var i = 1; i <=10; i++) {
<input type="radio" name="scores" id="i" value="i"> i
}
</script>
<input type="submit" name="mysubmit" value="Submit"/>
</form>
</body>
</html>
Thanks. I'm new to JS so I'm still learning a lot.
Use document.write
to output the HTML like so.
document.write('<input type="radio" name="scores" id="i" value="i"> i');
<html>
<body>
<h2 style="text-align:center">
On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?
</h2>
<form id="NPSform"; style= "text-align:center">
<script>
for (var i = 1; i <=10; i++) {
document.write('<input type="radio" name="scores" id="i" value="i">'+ i);
}
</script>
<input type="submit" name="mysubmit" value="Submit"/>
</form>
</body>
</html>
You can add all inputs to one string inside loop and then append it to HTML, also you should separate your js
and html
code
var inputs = '';
for (var i = 1; i <= 10; i++) {
inputs += '<input name="scores" type="radio" value="' + i + '" id="' + i + '">'+i+'';
}
document.getElementById('NPSform').insertAdjacentHTML('afterbegin', inputs);
<h2 style="text-align:center">On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?</h2>
<form id="NPSform" style="text-align:center">
<input type="submit" name="mysubmit" value="Submit" />
</form>
You can also create one div, set innerHTML
and use insertBefore
to add it to html
var inputs = '';
for (var i = 1; i <= 10; i++) {
inputs += '<input name="scores" type="radio" value="' + i + '" id="' + i + '">' + i + '';
}
var div = document.createElement('div');
div.innerHTML = inputs;
var submit = document.querySelector('#NPSform input');
submit.parentNode.insertBefore(div, submit);
<h2 style="text-align:center">On a scale from 1-10, how likely are you to recommend this site to a friend or colleague?</h2>
<form id="NPSform" style="text-align:center">
<input type="submit" name="mysubmit" value="Submit" />
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With