Andy
Andy

Reputation: 727

jquery loop to create elements with retained values

I recently asked a question about creating elements with jquery. Specifically I needed input boxes created/deleted depending on the value of a particular select box. This was answered quickly with a very nice solution as follows:

$('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);
});

This works very well. Is there a way to have the values remaining in the text boxes when the selection is changed? For example, lets say the select element value is set to '2' so that there are 2 input boxes showing. If there is input already entered in these boxes and the user changes the select element value to '3' is there a way to get the first 2 input boxes to retain their value?

Thanks for the help in advance

Andy

Upvotes: 2

Views: 674

Answers (2)

GlenCrawford
GlenCrawford

Reputation: 3389

The following line should work, nice and simple:

var value = ($("#id"+i).val() || '');
container.append('<input id="id'+i+'" name="name'+i+'" value="'+value+'" />');

Edited, thanks patrick.

Upvotes: 1

Luis Melgratti
Luis Melgratti

Reputation: 12050

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

         // append existing input if available
         if($("#id"+i).length){
            container.append($("#id"+i));
         }
         else {
             container.append('<input id="id'+i+'" name="name'+i+'" />');
         }
     }
     $('somewhere').html(container);
});

Upvotes: 1

Related Questions