简体   繁体   English

HTML输入的JavaScript生成

[英]Javascript generation of html inputs

<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 . 我希望输入文本的名称属性具有自动生成的形式answer1answer2answer3answer4answer5 ,但是所有输入字段的名称属性都显示常数str3

How to include html in javascript? 如何在javascript中包含html?

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. 同样,实际上不需要strstr1str3变量,并且可以简化您的代码。

So your generation function could look like: 因此,您的生成函数可能类似于:

function xyz(){
    for(var i = 1; i <= 5; i++){
        document.write('<input type=text name="answer' + i + '" />');
    }
}

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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