简体   繁体   中英

how to use javascript variables for html input name in javascript function?

 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?

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM