Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery loop to create elements

Tags:

jquery

loops

I have had no luck with this task so far so grateful for any help.

I have an html form, in which there is a small select menu (1-10) ie

<select>
    <option value = '1'>1</option>
    <option value = '2'>2</option>
    ...
    <option value = '10'>10</option>
</select>

depending on what value is selected i would like jquery to create (or remove) that number of input text boxes (with different names and id's). eg if 2 was selected these inputs would be created:

<input type = 'text' name = 'name1' id = 'id1' />
<input type = 'text' name = 'name2' id = 'id2' />

i look forward to your no doubt simple and elegant solutions! andy

like image 611
Andy Avatar asked Mar 30 '10 15:03

Andy


2 Answers

<select>
    <option value = '1'>1</option>
    <option value = '2'>2</option>
    ...
    <option value = '10'>10</option>
</select>
<div id="container">
</div>

For your markup.

Then

$('select').bind('change', function () {
    var val = parseInt($(this).val(), 10) + 1,
        str = '';

    for (var i=1; i<val;i++) {
        str += '<input type="text" name="name' + i + '" id="id' + i + '"/>';
    }

    $('#container').html(str);
});
like image 167
Matt Avatar answered Sep 20 '22 16:09

Matt


Something like this:

$('select').change(function() {
     var num = parseInt($(this).val(), 10);
     var container = $('<div />');
     for(var i = 1; i <= num; i++) {
         container.append('<input id="id'+i+'" name="name'+i+'" />');
     }
     $('somewhere').html(container);
});
like image 23
Tatu Ulmanen Avatar answered Sep 20 '22 16:09

Tatu Ulmanen