jQuery select list removes all options

91,717

Solution 1

this would do:

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

Solution 2

This works too.

$("#selectId option").remove(); 

Solution 3

$("#selectId").empty(); works for me.

The $("#selectId option").remove(); removed the select from the DOM.

Currently using jQuery JavaScript Library v1.7.1

Solution 4

The fastest way to accomplish this:

$("#selectId").empty();

Here are some tests: http://jsperf.com/find-remove-vs-empty

I take no credit for these tests. See this stack overflow question: How do you remove all the options of a select box and then add one option and select it with jQuery?

Solution 5

$("#selectId").options.length = 0;

That won't actually work as written because it's using a jQuery selector. It'd work if you used a straight DOM getElementById on the select list, though. Either AKX's or d.'s responses will set you right.

Share:
91,717
Richbits
Author by

Richbits

Updated on May 06, 2021

Comments

  • Richbits
    Richbits about 3 years

    I have a <select> list, which has been populated with several options, but want to remove those options to start again.

    I am using jQuery and have tried the following:

    $("#selectId").length = 0;
    

    But this seems to have no effect.

    Part of my problem is that I am using Firebug to debug the JavaScript, but the debugger does not break at the breakpoint, so I cannot see what is going on. Should it break when the JavaScript is within the <head> of my HTML file?

  • Rob Forrest
    Rob Forrest over 8 years
    This seems like the neater solution
  • Bryce
    Bryce about 7 years
    I like this better than the accepted answer because it is safer by removing the specific "option" tags.
  • therealprashant
    therealprashant almost 7 years
    doesnt this removes the <select> entirely? I would like to bring the select to the original state without any options
  • David Hedlund
    David Hedlund almost 7 years
    @therealprashant: .html sets the inner html of an element, so setting it to an empty string will remove any child nodes, but spare the dropdown list itself.