Andy
Andy

Reputation: 727

jquery loop to create elements

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

Upvotes: 14

Views: 40799

Answers (4)

kbro
kbro

Reputation: 4991

This uses $.map() to iterate over an array using the index to emulate the "0..N" range operator of languages like Perl and PHP. Since $.map() returns an array of the return values of each call to the callback function, we can pass this straight to $().html() to set the content of the parent element. Neat?

Just make sure you declare the callback function's 'object' and 'index' parameters in the correct order - they're the opposite way around to $.each()!

HTML

<div id='container'></div>

JS

const HOW_MANY = 10;

$('#container').html(
  $('<select/>', { id: 'selection' }).html(
    $.map(Array(HOW_MANY), function(o,i) {
      i++;  // because array indices run from 0
      return $('<option/>', { value: i }).text(i);
    }) // map
  ) // <select/>
);

FIDDLE

https://jsfiddle.net/kmbro/xxtbjgzo/

Upvotes: 1

Alistair
Alistair

Reputation: 1979

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.

Upvotes: 9

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124878

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);
});

Upvotes: 31

Matt
Matt

Reputation: 75327

<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);
});

Upvotes: 3

Related Questions