Adding Multiple Inputs
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
Solution 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 />')
}
});
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text"id="inp1"name="inp1"placeholder="Number of inputs"><buttontype="button"name="btn"id="btn">Add</button><tableid="table"name="table"><tbody><tr><td></td></tr></tbody></table>
Solution 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>")
}
})
})
<inputtype="text"id="inp1"name="inp1"placeholder="Number of inputs"><buttontype="button"name="btn"id="btn">Add</button><tableid="table"name="table"><tbody></tbody></table><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Post a Comment for "Adding Multiple Inputs"