Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add input fields in form when dropdown option selected

How to add fields in form dynamically

so my form looks like :

<form action="/reservation-add" method="post">
<select id="dropdownlist">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input></input>
</form>

If selected e.g 3 it should append 3 new inputs (could be array to take all of values ) I know that I have to use javascript but I don't know how.

like image 538
binar Avatar asked Jul 08 '15 11:07

binar


1 Answers

Use this way:

$("#dropdownlist").change(function () {
    var numInputs = $(this).val();
    for (var i = 0; i < numInputs; i++)
        $("#inputArea").append('<input name="inputs[]" />');
});

Have another div, with the ID "inputArea":

<div id="inputArea"></div>

Snippet

$("#dropdownlist").change(function () {
  var numInputs = $(this).val();
  for (var i = 0; i < numInputs; i++)
    $("#inputArea").append('<input name="inputs[]" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="dropdownlist">
  <option>Select...</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>
<div id="inputArea"></div>
like image 191
Praveen Kumar Purushothaman Avatar answered Oct 19 '22 18:10

Praveen Kumar Purushothaman