Siwan
Siwan

Reputation: 59

Jquery, adding input element

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.

Upvotes: 0

Views: 205

Answers (1)

Matt
Matt

Reputation: 75317

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

Upvotes: 3

Related Questions