1
 function f1(){
 document.getElementById("comment_show").innerHTML
 ="<form action='c.php' method='post'>a:"+
 "<input type='text' name='d1'> <br>"+
 "<textarea name='comment' rows='5' cols='100'> </textarea> <br>"+

 "b:"+
 "<input type='text' name='d2'> <br>"+
 "<textarea name='comment' rows='5' cols='100'> </textarea> <br>"+

 "c:"+
 "<input type='text' name='d3'> <br>"+
 "<textarea name='comment' rows='5' cols='100'> </textarea> <br>"+

 "<input type='submit' name='s1' value='s1'> <br><br><br><br>"+

 "</form>";
 }

How to replace d1,d2,d3 with javascript variables in order to make it as a loop?

1
  • 1
    "mystring" + myVariable + "myOtherString" Commented Dec 30, 2015 at 4:55

2 Answers 2

2

Here is how you would automate the creation of your inputs:

var inputsCount = 3;

var inputs = "";
var LETTER_START = "a".charCodeAt(0) - 1;
for (var i = 1; i <= inputsCount; i++) {
    inputs += String.fromCharCode(LETTER_START + i) + ":"+
    "<input type='text' name='d" + i + "'> <br>"+
    "<textarea name='comment' rows='5' cols='100'> </textarea> <br>";
}


var inner = "<form action='c.php' method='post'>" +
        inputs +
        "<input type='submit' name='s1' value='s1'> <br><br><br><br>" +
        "</form>";

document.getElementById("comment_show").innerHTML = inner;
Sign up to request clarification or add additional context in comments.

3 Comments

I also have tired this before. But, it does not work so that I post it in stackoverflow. Now, I tried this method again and luckily this time, it works. I don't figure out why it did not work yesterday. Anyway, it works. Thank you.
var d=1; function add(){ d = d+1; var temp2 = "<form action='c.php' method='post'> <font size='5pt'>"; for(var i = 1; i<=d ; i++){ temp2 = temp2+"d" + i + ":" + "<input type='text' name='d" + i + "'> <br>"+ "<textarea name='comment" + i + "'" rows='5' cols='100'> </textarea> <br>"; } temp2 = temp2+"</font>"+"</form>"; document.getElementById("comment_show").innerHTML = temp2; } this time, it doesn't work. Help!
I knew the problem. I missed out " . It works again. Thanks.
0

You could use an array to hold the names, then use jquery .each to generate the html string. Or you could just do a plain old for loop on the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.