cooper
cooper

Reputation: 623

dynamically creating Input text boxes

I have select box with options 1 to 10 as below .If i select a number then I need to dynamically populate those many input text boxes just below the select box, with each input text box having its label to its left e.g label1, label2 etc.

<form>
 <select>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
 </select> 
 <input type="submit" value="Submit">
</form>

EDIT

If i wrap my select box & submit button inside <form></form> , then Jquery is creating the input text boxes outside the form.. any work around for this.In such cases, should we still create a placeholder using <div> Or we should create a placeholder using <tr id=''>. Thanks

Thanks

Upvotes: 0

Views: 1125

Answers (3)

Sanjeevi Rajagopalan
Sanjeevi Rajagopalan

Reputation: 232

Checkout this fiddle code.

$('#mySelect').on('change', function(){
    var $textboxes = '';
    for(var i = 1; i <= $(this).val(); i++)
    {
        $textboxes += '<label>Textbox ' + i + '</label><input></input>';
    }
    $('#holder').html($textboxes);
});

Upvotes: 0

Nishu Tayal
Nishu Tayal

Reputation: 20820

Use it :

HTML code :

<select id="select">
   <option>select</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select> 
<div id = "textbox_div"></div>
<input type="submit" value="Submit">

Jquery code :

jQuery('#select').change(function(){
    var val = jQuery(this).val();
    var innerhtml = '';
    for(var i = 0;i<val;i++){
        innerhtml += "<label> label"+(i+1)+" :</label><input type='text' id='textbox"+(i+1)+"' size=50></br>";
    }
    jQuery('#textbox_div').html(innerhtml);
});

Here is the working demo : http://jsfiddle.net/g3Be3/

Upvotes: 1

TGH
TGH

Reputation: 39248

This is certainly possible using bare bones JQuery, but I would encourage you to look into a template based solution: Two frameworks that come to mind are KnockoutJS and HandlebarsJS. The key point here is that it's nice to avoid looping out markup using JQuery, but instead use template based data binding:

http://handlebarsjs.com/

http://knockoutjs.com/

Granted, it might be overkill for this particular problem, but I would argue that it's a very useful technique to learn for more advanced scenarios.

Upvotes: 0

Related Questions