Upendra Joshi
Upendra Joshi

Reputation: 611

display textboxes when radio button selected

this is my html code :

<div>
    <label for="accompanying_person" class="col-sm-4 col-form-label">Select number of accompanying person</label>
       <div class="col-sm-8">
               <input type="radio" name="accompanying_person" id="accompanying_person" value="1"> 1
               <input type="radio" name="accompanying_person" id="accompanying_person" value="2"> 2
               <input type="radio" name="accompanying_person" id="accompanying_person" value="3"> 3
       </div>
 </div>

how to display number of text boxes that are equal to radio button value. for example, display 2 text boxes when "2" is selected OR display 3 text boxes when "3" is selected using JavaScript?

Upvotes: 2

Views: 2383

Answers (2)

Bhargav Chudasama
Bhargav Chudasama

Reputation: 7165

try this code

$(document).ready(function() {

  $(this).click(function() {
    $('#textbox').html('');
    var val = $('input[name=accompanying_person]:checked').val();
    for (var i = 1; i <= val; i++) {
      $('#textbox').append('<input type="text" id="' + i + '"><br>');
    }
  });
});
input {
  margin-bottom: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label for="accompanying_person" class="col-sm-4 col-form-label">Select number of accompanying person</label>
  <div class="col-sm-8">
    <input type="radio" name="accompanying_person" id="accompanying_person" value="1"> 1
    <input type="radio" name="accompanying_person" id="accompanying_person" value="2"> 2
    <input type="radio" name="accompanying_person" id="accompanying_person" value="3"> 3

  </div>
  <div id="textbox"></div>
</div>

Upvotes: 3

31piy
31piy

Reputation: 23859

You can listen to the change event of the radio buttons and run a loop through the value to prepare the text boxes dynamically.

Note that the parseInt actually converts the value to integer, since it will be a string when fetched using .val().

Also, do not use the same ID for elements in an HTML page.

$("input[type=radio][name=accompanying_person]").change(function() {
  var persons = parseInt($(this).val());
  var boxes = [];
  
  for (var i = 0; i < persons; i++) {
    boxes.push("<input type='text'>");
  }
  
  $("#boxes").html(boxes.join(""));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label for="accompanying_person" class="col-sm-4 col-form-label">Select number of accompanying person</label>
  <div class="col-sm-8">
    <input type="radio" name="accompanying_person" id="accompanying_person" value="1"> 1
    <input type="radio" name="accompanying_person" id="accompanying_person" value="2"> 2
    <input type="radio" name="accompanying_person" id="accompanying_person" value="3"> 3
  </div>
</div>

<div id="boxes">
</div>

Upvotes: 3

Related Questions