josefermin josefermin - 2 months ago 9
HTML Question

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

Answer

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>