最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript variable as html tag name - Stack Overflow

programmeradmin2浏览0评论

Here is my code..

<!DOCTYPE html>
<html>
<script>
function genbox()
{
var i;
var myarray = new Array();
myarray[0] = "name";
myarray[1] = "dob";
myarray[2] = "email";
for (i=0;i<myarray.length;i++)
{
document.write('<input name="' + myarray[i] + '"/>');
}
}
</script>
<body>
<input type="button"  value="create" onclick="genbox();">
</body>
</html>

Old:I want the textbox name as the values of the array such as name, dob etc. but all i'm getting is 3 textboxes with the same name "myarray[i]". Please help me.

Okay, Here we go, I'm pretty new to js. After clicking the button it creates 3 textboxes, but, the button disappears, What should I do to keep the button alive???

Here is my code..

<!DOCTYPE html>
<html>
<script>
function genbox()
{
var i;
var myarray = new Array();
myarray[0] = "name";
myarray[1] = "dob";
myarray[2] = "email";
for (i=0;i<myarray.length;i++)
{
document.write('<input name="' + myarray[i] + '"/>');
}
}
</script>
<body>
<input type="button"  value="create" onclick="genbox();">
</body>
</html>

Old:I want the textbox name as the values of the array such as name, dob etc. but all i'm getting is 3 textboxes with the same name "myarray[i]". Please help me.

Okay, Here we go, I'm pretty new to js. After clicking the button it creates 3 textboxes, but, the button disappears, What should I do to keep the button alive???

Share Improve this question edited Mar 2, 2013 at 9:59 MEP asked Mar 2, 2013 at 9:16 MEPMEP 171 silver badge8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

try this line in the loop instead:

document.write('<input name="' + myarray[i] + '"/>');

Working jsfiddle is here.

You can't insert JavaScript variables inside a string and expect the interpreter to extract its value (as some languages do, like PHP). Build your string using concatenation instead:

"<input name='" + myArray[i] + "'/>"

You should go through some basic tutorials about javascript, try http://www.codecademy./

Here's the code, however you shouldn't add html with document.write, there are other, better methods to do it.

    var i,
        myarray = ["name", "dob", "email"];

    for (i = 0, ilen = myarray.length; i < ilen; i++) {
        document.write('<input name="' + myarray[i] + '"/>');
    }
发布评论

评论列表(0)

  1. 暂无评论