根据用户在JavaScript函数中的输入创建文本字段
我想根据用户的输入创建文本字段,并通过JavaScript函数显示文本字段,但这段代码不起作用根据用户在JavaScript函数中的输入创建文本字段,javascript,html,Javascript,Html,我想根据用户的输入创建文本字段,并通过JavaScript函数显示文本字段,但这段代码不起作用 <html> <head> <title>Create text Fields according to the users choice!</title> <script type="script/JavaScript"> function createTextField(){
<html>
<head>
<title>Create text Fields according to the users choice!</title>
<script type="script/JavaScript">
function createTextField(){
var userInput = parseInt(document.form2.txtInput.view);
for(var i=0; i<=userInput;i++)
{
document.write('<input type="text">');
}
}
</script>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
请替换此行:
var userInput = parseInt(document.form2.txtInput.view);
到
函数createTextField{
//alertdocument.getElementById'txtInput'。值;
var userInput=parseIntdocument.getElementsByName'txtInput'[0]。值;
forvar i=0;i变化:
var userInput = parseInt(document.form2.txtInput.view);
致:
给输入文本框一个我用过的id,但它可以是任何东西。
我认为您还需要更改循环,当我键入2时,它创建了3个输入,而不是2个输入。您不应该使用document.write。正确的方法是将输入附加到div
演示
HTML:
JavaScript:
Jquery是添加DynamicInput/div易于操作的DOM的更好选项。 检查以下代码
<div class="box">
<label> Enter input value </label>
<input type="number" id="in_num"/>
<button type="button" id="submit"> submit </button>
<h3> Append input values</h3>
<div id="dynamicInput"></div>
</div>
$(document).ready(function(e){
$('#submit').click(function(){
var inputIndex = $('#in_num').val();
for( var i=0; i<inputIndex; i++)
{
$('#dynamicInput').append('<input type=text id=id_'+ i +'/>');
}
});
});
演示URl:他提到的Id在哪里?感谢您的详细回答!
var userInput = parseInt(document.getElementById("txtInput").value);
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>Input:
<input type="text" name="txtInput" />
<input type="button" name="btnInput" value="Create" />
<div></div>
</form>
var btn = document.getElementsByTagName("input")[1];
btn.onclick = function () {
var userInput = parseInt(document.getElementsByTagName("input")[0].value, 10);
for (var i = 0; i <= userInput - 1; i++) {
document.getElementsByTagName("div")[0].innerHTML += "<input type='text' />"
}
};
<div class="box">
<label> Enter input value </label>
<input type="number" id="in_num"/>
<button type="button" id="submit"> submit </button>
<h3> Append input values</h3>
<div id="dynamicInput"></div>
</div>
$(document).ready(function(e){
$('#submit').click(function(){
var inputIndex = $('#in_num').val();
for( var i=0; i<inputIndex; i++)
{
$('#dynamicInput').append('<input type=text id=id_'+ i +'/>');
}
});
});