tags:

views:

51

answers:

1

hi everyone, i have successfully added input element into div, which looks like this :

$(document).ready(function() {
  $('#jumlah').change(function() {
 var jum = $('#jumlah').val();

 for(i=1;i<=jum; i++){
     $('#jawaban').append('<label>Jawaban Soal ' + i + ' : </label><input type="text" name="jawab'+i+'" id="jawab[]" size="2" maxlength="1" /><br>');
 }
  });
});

and some my HTML codes are :

<select name="jumlah" id="jumlah" class="test">
    <option value="0" selected="selected">choose value</option>
    <?php
  for($i=1;$i<=20;$i++)
   echo("<option value=\"$i\">$i</option>");
 ?>
</select>

<div id="jawaban"></div>

but when i choose different value, it appends more input elements under the first ones, for example, if i choose option 2 and then option 3 it will look like :

Jawaban Soal 1 : <input />
Jawaban Soal 2 : <input />
Jawaban Soal 1 : <input />
Jawaban Soal 2 : <input />
Jawaban Soal 3 : <input />

Please help, i'm still junior in Jquery. I'm looking forward to your respond.

+3  A: 

I'm guessing you want the old ones to disappear, in which case you should empty the jawaban div first.

$(document).ready(function() {
  $('#jumlah').change(function() {
     var jum = $('#jumlah').val();

     $('#jawaban').empty();

     for(i=1;i<=jum; i++){
         $('#jawaban').append('<label>Jawaban Soal ' + i + ' : </label><input type="text" name="jawab'+i+'" id="jawab[]" size="2" maxlength="1" /><br>');
     }
  });
});

You (infact a considerable amount of people), should cache the jQuery objects you build. Each time you use $('someSelector') in your code, jQuery re-selects your elements, and returns a new object for you each time. this is none trivial!

$(document).ready(function() {
  $('#jumlah').change(function() {
     var jum = +$('#jumlah').val(); // convert this to an integer (it's a string otherwise)
     var jawaban = $('#jawaban').empty();

     for(var i=1;i<=jum; i++){ // don't forget to initialize i!
         jawaban.append('<label>Jawaban Soal ' + i + ' : </label><input type="text" name="jawab'+i+'" id="jawab[]" size="2" maxlength="1" /><br />');
     }
  });
});
Matt
wow, it works like charm ! Thanks Matt
Siwan
@Siwan: Good to hear! I recommend you take a look at the suggestions I made in my second example to further improve your code!
Matt
sure Matt, i've taken your suggestions into my code. But another issue occurs, i want to make sure that those dynamically-created input elements are not empty and must be alphanumeric when submitted, how to validate that ?
Siwan