Reputation: 23
<body>
<form action="insertquestion.php" method="POST">
<script>
function xyz(){
var str="answer";
var str1=1;
for(var i = 0; i < 5; i++){
var str3 = str+str1;
document.write('<input type=text name=str3 />');
str1++;
}
}
xyz();
</script>
<input type="submit" value="Submit"/>
</form>
</body>
I wanted the name attribute of the input text to be of the form answer1
, answer2
, answer3
, answer4
, answer5
to be generated automatically but name attribute of all the input feilds are showing the constant value str3
.
How to include html in javascript?
Upvotes: 1
Views: 48
Reputation: 2687
Look this:
label{
float:left;
}
<form action="insertquestion.php" method="POST">
<script>
function xyz(){
var str="answer";
for(var i = 0; i < 5; i++){
document.write('<label>Answer ' + i + ': </label><input type=text name="answer' + i +'" /><br><br>');
}
}
xyz();
</script>
<br><br><input type="submit" value="Submit"/>
</form>
Upvotes: 0
Reputation: 26846
You're setting your inputs name to the same value instead of concatenating this name from variables.
Also str
, str1
and str3
variables are in fact not needed to do it, and your code can be simplified.
So your generation function could look like:
function xyz(){
for(var i = 1; i <= 5; i++){
document.write('<input type=text name="answer' + i + '" />');
}
}
Upvotes: 1