开发者

Dynamically populating a dropdown with jQuery

How do I remove all the values from a dropdown list using jQuery?

idnum = "item-7";

which populates a dropdown with 7 items. I could have an "item-3" which would populate a dropdown with three items. What I'm trying to do is select a button which could have an id valu开发者_如何学运维e of "item-X" where X is the number of entries to populate so it could be different based on whatever button I click. I want to clear the select list and repopulate it with a different number on each button click.

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're both not working.


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

will clear your options.


if you want to populate with new option don't use appendTo().

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


To remove your options, you can also do :

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


Have you tried

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜