2

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

2
  • There is also the case where a lower number is selected and I assume the input boxes need to be truncated (from the highest numbered ID back). What have you tried so far? Commented Apr 28, 2010 at 11:19
  • Heads up. Putting container.append inside the for loop is very bad for performance. Rather concatenate all the markup inside the loop (using += or array.push) and use that markup in one .append operation after the loop. Commented Apr 28, 2010 at 11:44

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This would insert undefined if there's no existing input. (Also "id" is in the wrong place. Should be "#id".) You could test for undefined first, like var value = ($("#id"+i).val() || '');.
1
$('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);
});

1 Comment

This line if($("#id"+i)) {... will always return true. You would need if($("#id"+i).length){ instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.