Jordan Andrews
Jordan Andrews

Reputation: 163

create a number of form items based on user input

I have a value inputted by the user. How do I create a certain number of form items for the user to fill out, in either javascript/jQuery or PHP?

Eg.

<select id = "Fooinput" name = "Foo">
    <option value = "0">0</option>
    <option value = "1">1</option>
    <option value = "2">2</option>
    <option value = "3">3</option>
    <option value = "4">4</option>
</select>
<button id ="fooclick">Button</button>
<div id="fillout"></div>

and something like this in jQuery

$(document).ready(function(){
  var inputnum = $("Fooinput").val();
  $("#foobutton").click(function(){
      for (var i=0; i<inputnum;i++){
          $("#fillout").append('<select id="uniqueid">OPTIONS</select>');
      } 
  });
}); 

I'm happy to see a solution in either jQuery or PHP, I just don't understand how I can later retrieve the values by giving all the select boxes a unique ID.

Upvotes: 1

Views: 184

Answers (2)

Sebastien B.
Sebastien B.

Reputation: 476

This code will do the trick

NOTE : I moved the var inputnum = $("Fooinput").val(); inside of the click event because as OP you will get value on page load not on click.

 $(document).ready(function(){

  $("#foobutton").click(function(){
      var inputnum = $("Fooinput").val();
      for (var i=0; i<inputnum;i++){
          $("#fillout").append('<select id="uniqueid-'+$i+'">OPTIONS</select>');
      } 
  });
}); 

Upvotes: 1

Pratik Joshi
Pratik Joshi

Reputation: 11693

Give unique id inputnum in loop

$("#fillout").append('<select id="uniqueid'+inputnum+'" class="Dropdown">OPTIONS</select>');

So id will be unique like uniqueid0 , uniqueid1 etc.

Then you can access it , using unique id , Use event like

$(".Dropdown").click(function(){
    $(this).attr(id);
});

Check using Inspect element, Fiddle , You get unique id , here in this case i hardcoded 1 But same value will be looped in your code.

Upvotes: 1

Related Questions