Mr.abing_da_student Mr.abing_da_student - 8 days ago 7
Javascript Question

javascript drop down list equal to the same number of textbox

I have one drop-down list that has numbers 1-10 and a proceed button.

What I want is, when the user select a specific number and the user click the proceed button, it should display a number of textboxes equal to the number of selected in the drop-down list.

is it possible to doit with a loop? or any suggestions?

Answer

Here is an option - using jQuery cos its much cooler than just plain JS - first determine the number of textboxes required based on the value of the select list. Then create a string with the required number of textboxes and third - apply that HTMl to the empty div. Note that the reason for building the textboxes as a string and then adding it to the div is that this requires only one alteration to the DOM - doing it on each iteration would require altering the DOM numerous times. Its fine if you don't want to use jQuery - as the other answers demonstrate - all things done in jQ can be done in JS - but its just more fun to use.

$(document).ready(function(){
  $('#selection').change(function(){
    var num = $(this).val();
    var HTML='';
    for(i = 0; i < num; i++){
      HTML += "<input type='text' name='textBox"+i+"' /><br/>"
      }
    $('#newDiv').html(HTML);
  })                  
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for = "selection"> Enter the number of textboxes required</label>
<select id="selection">
  <option disabled selected></option>
   <option>1</option>
   <option>2</option>
   <option>3</option>
   <option>4</option>
   <option>5</option>
  </select>

<hr/>
<div id="newDiv"></div>

Comments