开发者

remove() in jquery is not working

Hi can anyone tell me why remove() is not working in the following code

  $("#mydropdown_for_month").change(function(){
  $("#mydropdown_for_day").empty();
   for (var i=1; i<=31; i++)
   {options += '<option>' + i+'</option>';}
   $('#mydropdown_for_day').after().html(options);

I have two select boxes with ids mydropdown_for_month and mydropdown_for_day. The problem is that when I click any month in the first dropdown , second dropdown normally shows all the dates from f开发者_运维技巧or loop as i have mentioned but when i again change the month say from feb to april the second dropdown show dates from 1 to 31 twice (may be 1 to 31 for first i select month and 1 to 31 again for the second time when i select april). so to solve this i put the following statement $("#mydropdown_for_day").empty(); so that on every selection from the first dropdown , second dropdown's all previous options get removed but no use.

Please help me where am i making mistake?


If your goal is to replace the options currently in the select box with new options, I'd do it like this:

$("#mydropdown_for_month").change(function(){
    var options, i;

    options = $("#mydropdown_for_day")[0].options;
    options.length = 0;
    for (i = 1; i <= 31; i++) { // I'm guessing you'd want to use a different upper limit here for different months
        options[options.length] = new Option(i, i);
    }
});

It's rather more direct than building up an HTML string. The Option constructor accepts up to four arguments: The text to display, the value, whether the option is the default, and whether it's selected. The options pseudo-array (it's not really an array) on the raw select element contains the options. You can add to it by assigning to an index above the last-used index (as above), or by calling its add method (not push as it would be with an array).


Update: Below you've asked

but what is wrong with my code ... where is the mistake?

Fundamentally, the mistake is that that's not how you add/remove options; hence the above. It seems like it should work (after all, that's how you specify them in HTML), but in my experience it doesn't work well-cross browser. The above works in every browser I've ever seen.

Other specifics:

  • You've called after with no arguments, which doesn't make any sense; after is for inserting content after things, so you have to say what the content is. I wouldn't be surprised if there were an error because of that.
  • You've never declared or initialized your options variable.


If you want to remove all options you could use:

 $("#mydropdown_for_day option").remove()
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜