单击按钮时如何显示一些文本字段?

时间:2017-09-29 09:42:27

标签: javascript jquery html

我想制作一个代码,当我输入数字然后点击提交时,它会显示一些文本字段作为输入的数字。

这是代码示例:

<input type="number" id="myNumber" value="2">

<p>Click the button to get some textfield.</p>

<button">submit</button>

当我点击提交按钮(例如:输入数字= 2)时,这将显示两个文本字段,如代码:

<input type="text" class="form-control" id="text1" name="text1">
<input type="text" class="form-control" id="text2" name="text2">

3 个答案:

答案 0 :(得分:1)

试试这个简单的例子。

document.querySelector("button").addEventListener("click", function() {
  var number = parseInt(document.getElementById("myNumber").value);

  var html = "";
  for (var counter = 0; counter < number; counter++) {
    html += '<input type="text" class="form-control" id="text' + counter + '" name="text1' + counter + '">'
  }
  document.getElementById("allNewTextBoxes").innerHTML = html;
});
<input type="number" id="myNumber" value="2">\
<p>Click the button to get some textfield.</p>
<button>submit</button>
<p id="allNewTextBoxes"></p>

答案 1 :(得分:0)

将两个文本字段放在div

<input type="number" id="myNumber" value="2">
<p>Click the button to get some textfield.</p>
<button>submit</button>

<div id="show" style="display:none;">
  <input type="text" class="form-control" id="text1" name="text1">
  <input type="text" class="form-control" id="text2" name="text2">
</div>

然后使用toggle方法显示文本字段

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#show").toggle();
    });
});
</script>

答案 2 :(得分:0)

<!DOCTYPE html>
<html>
<head>
<title>demo</title>
</head>
<body>
<form method="post">
<label>Number:</label>
<input type="text" name="number">
<input type="submit" name="submit" value="click me!">
</form>
<?php
if (isset($_POST['submit'])) {
$value=$_POST['number'];
for ($i=1; $i < $value; $i++) {
echo "<br>";
echo "<label>label".$i."</label>";
echo "<input type='text' name=text".$i." id=text".$i." class='form-control'>";
}
}
?>
</body>
</html>