tags:

views:

237

answers:

4

Dear all, 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

+8  A: 

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);
});
Tatu Ulmanen
no doubt simple and elegant solution :)
Michel
Does Jquery actually knows that when you append html to a closed DIV ('<div />') that it should create <div>appended html</div> ?
Michel
@Michel, yes. `$('<div />')` just creates an empty div element and is equivalent to `$('<div></div>')` or `$(document.createElement('div'))`.
Tatu Ulmanen
@tatu: nice, Jquery keeps surprising me in a positive way
Michel
+1  A: 
<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);
});
Matt
A: 

thank you both for your excellent solutions - both worked a charm! Andy

Andy Simpson
A: 

To slightly modify Tatu's answer,

$('select').change(function() {
 var num = parseInt($(this).val(), 10);
 var container = $('<div />');

 for(var i = 1; i <= num; i++) {
     $('<input />', {
         id: "id" + 1,
         name: "name" + 1
     }).appendTo(container);
 }

 $('somewhere').html(container);
 });

This way is faster and a bit easier to read. The reason it is faster is because jQuery heavily caches creating elements. It caches "<input />" the first time and then just uses the cached object to create more of them. It can do this because the text doesn't change. However, it can't do this caching with append (or html not created by calling the main jquery function $ AFAIK) since due to the ids they are unique each loop. See John Resig's 'Things you might not know about jQuery' speech for info on this.

Alistair