问题
I want to add multiple text inputs, but how? Just putting the number of inputs I want on screen is the only input that I have declared in HTML.
Let's say that I type the number 3
then when I press the button. The number of inputs I entered should appear. It actually only adds one input per click and ignores the typed data in the input. How can I fix this?
<!DOCTYPE html>
<html>
<head>
<title>HTML</title>
</head>
<script src="js/jquery-3.1.0.min.js"></script>
<script src="js/test.js"></script>
<body>
<input type="text" id="inp1" name="inp1" placeholder="Number of inputs">
<button type="button" name="btn" id="btn">Add</button>
<table id="table" name="table">
<tbody></tbody>
</table>
</body>
</html>
$(document).ready(function() {
$(document).on('click', '#btn', function() {
$('#table tbody').append('<input></input>')
});
});
回答1:
Firstly note that you cannot just append an input
as a child of a tbody
. You need to place it within a td
, which in turn needs to be in a tr
. Also note that input
is self closing, so you should append only <input />
.
To achieve what you need you can use a simple for
loop, using the entered value as the iteration limiter (once you've parsed it to an integer). Try this:
$(document).ready(function() {
$(document).on('click', '#btn', function() {
for (var i = 0; i < parseInt($('#inp1').val(), 10); i++) {
$('#table tbody td').append('<input />')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inp1" name="inp1" placeholder="Number of inputs">
<button type="button" name="btn" id="btn">Add</button>
<table id="table" name="table">
<tbody>
<tr><td></td></tr>
</tbody>
</table>
回答2:
Try this:
$(document).ready(function() {
$("#btn").on("click",function(){
var number = $("#inp1").val();
number = parseFloat(number);
for (var i=1; i <= number; i++){
$("#table tbody").append("<br>Number " + i + " : <input type=text><br>")
}
})
})
<input type="text" id="inp1" name="inp1" placeholder="Number of inputs">
<button type="button" name="btn" id="btn">Add</button>
<table id="table" name="table">
<tbody></tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
来源:https://stackoverflow.com/questions/39808463/adding-multiple-inputs