Dynamically populate dropdown with jQuery

How to remove all values ​​from a dropdown using jQuery?

idnum = "item-7";

which fills a drop-down list of 7 elements. I could have "item-3" that populated the drop-down list with three elements. What I'm trying to do is select a button that can have an id value of "item-X", where X is the number of entries that can be different, based on any button that I click. I want to clear the selection list and re-populate it with a different number each time I press the button.

Here is my code:

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

 // alert('I was clicked, my id is ' + $(this).attr('id')); 
 var idnum = $(this).attr('id');
 var pos = idnum.lastIndexOf("-");
 var num = idnum.substring(pos + 1);

 // alert("You have " + num);

 // var numbers = [1, 2, 3, 4, 5]; 
 var numbers = new Array(num - 1);

 for (i = 0; i < num; i++) {
   numbers[i] = i + 1;
 }

 for (i=0;i<numbers.length;i++){ 
   $('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items'); 
 }

I tried empty () and remove (), and they both do not work.

0
source share
4 answers
$('#items').html('');

will clear your options.

+4
source

, appendTo().

var opt='';
for (i=0;i<numbers.length;i++){ 
   opt += '<option value="'+i+'">'+i+'</option>'; 
}
$('#items').html(opt);
+1

, :

$('# items > option'). remove();

+1

You tried

$('#items').children().remove(); 
0
source

All Articles