Skip to content Skip to sidebar Skip to footer

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 />')
    }
  });
});
<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>

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>")
            
        }
        
    })
    
    
})
<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>

Post a Comment for "Adding Multiple Inputs"