1228

Using core jQuery, how do you remove all the options of a select box, then add one option and select it?

My select box is the following.

<Select id="mySelect" size="9"> </Select>

EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val.)

$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');

EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery.

var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";

EDIT: selected answer was close to what I needed. This worked for me:

$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;

But both answers led me to my final solution..

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Jay Corbett
  • 28,091
  • 21
  • 57
  • 74

28 Answers28

1858
$('#mySelect')
    .find('option')
    .remove()
    .end()
    .append('<option value="whatever">text</option>')
    .val('whatever')
;
nickf
  • 537,072
  • 198
  • 649
  • 721
Matt
  • 31,662
  • 4
  • 34
  • 33
  • 3
    @nickf: I have the same problem, but I need to add a set of checkboxes rather than one on change of dropdown but my checkboxes are coming from xml. this doesn't work – defau1t Jan 15 '12 at 11:32
  • 14
    Note you could also break up the option/attr/text like: `.append($("").attr("value", '123').text('ABC!')` – Brock Hensley Jun 27 '13 at 21:58
  • 1
    @BrockHensley, I believe the true elegance of this answer is proper chaining in combo with the end() function. Your suggestion will work as well. From jQuery API Documentation: "Most of jQuery's DOM traversal methods operate on a jQuery object instance and produce a new one, matching a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack. If we need an older element set, we can use end() to pop the sets back off of the stack." – Anthony Mason Oct 01 '15 at 19:03
  • 1
    this was the only way I was able to rebuild my menu and change the selected option in jQuery Mobile on PhoneGap for iOS. Refreshing the menu afterwards was also required. – xited Dec 28 '15 at 22:26
  • 3
    @BrockHensley you could even go so far as `.append($("", {'value':'123'}).text('ABC!')` – vahanpwns Apr 09 '16 at 21:17
  • even simple append. category.append($('', { value: Id, text: Name, selected: categoryid == Id })) – sairfan Mar 26 '18 at 20:26
  • Why not `$('#mySelect OPTION').remove().append('').val('whatever')` ? – Volomike Sep 19 '19 at 08:34
  • after this I need to update selectpicker `$('#mySelect').selectpicker('refresh');` – Rafael Guimarães Sep 21 '21 at 16:04
805
$('#mySelect')
    .empty()
    .append('<option selected="selected" value="whatever">text</option>')
;
vzwick
  • 11,008
  • 5
  • 43
  • 63
Mahzilla
  • 8,059
  • 1
  • 15
  • 3
  • 38
    Just out of curiosity, is 'empty' faster than 'find'? Seems like it would be -- because the 'find' would use a selector and 'empty' would just brute force empty the element. – Dan Esparza Oct 14 '10 at 21:11
  • 58
    @DanEsparza I made you a jsperf; `empty()` turned out faster of course ;) http://jsperf.com/find-remove-vs-empty – vzwick Apr 08 '12 at 14:12
  • I got a wierd glitch with this solution. The populate part of it is okay, but when I try to select a value (in my case a day), I can console log the value, but the shown value in the select field stay in the first value.... I can't resolve it:/ – Zsolt Takács Oct 07 '16 at 13:42
  • 6
    @TakácsZsolt Maybe you should add a `.val('whatever')` at the end of the chain as in Matt's answer. – Cave Johnson Dec 30 '16 at 17:32
  • .empty() works with materialize, whereas .remove() did not work –  Dec 30 '18 at 23:58
  • 1
    `empty()` will remove everything, even comments and `find("option")` will not. Just a little comment... =D – Eduardo Lucio May 29 '21 at 16:49
159

why not just use plain javascript?

document.getElementById("selectID").options.length = 0;
Anand
  • 5,323
  • 5
  • 44
  • 58
Shawn
  • 3,031
  • 4
  • 26
  • 53
  • 9
    I agree that this is the simplest solution for removing all of the options, but that only answers half of the question... – Elezar Aug 04 '16 at 03:17
  • 6
    Wouldn't this create a memory leak? The option elements are now inaccessible but still allocated. – Synetech Mar 06 '19 at 19:57
111

If your goal is to remove all the options from the select except the first one (typically the 'Please pick an item' option) you could use:

$('#mySelect').find('option:not(:first)').remove();
mauretto
  • 3,183
  • 3
  • 27
  • 28
  • 14
    This should be the answer. All others intentionally removed the first with a view of recreating it afterwards, which I don't like; it also implies that they have stored the first option somewhere first too. –  Jan 23 '15 at 14:21
  • 1
    The ultimate answer, thank you!! – Herman Aug 04 '23 at 14:02
86

I had a bug in IE7 (works fine in IE6) where using the above jQuery methods would clear the select in the DOM but not on screen. Using the IE Developer Toolbar I could confirm that the select had been cleared and had the new items, but visually the select still showed the old items - even though you could not select them.

The fix was to use standard DOM methods/properites (as the poster original had) to clear rather than jQuery - still using jQuery to add options.

$('#mySelect')[0].options.length = 0;
row1
  • 5,568
  • 3
  • 46
  • 72
  • 7
    I had to use this method in ie6 as well because .empty() caused my select box that was contained in a hidden container to become visible even while the parent was hidden. – Code Commander Jan 04 '11 at 21:41
  • 3
    This method also turns out to be a tiny bit (around 1%) more performant: http://jsperf.com/find-remove-vs-empty – vzwick Apr 08 '12 at 14:20
  • 4
    +1 this is the most readable (in my opinion) and in jsPerf link (@vzwick linked) the accepted answer was 34% slower (Opera 20) – Morvael Mar 14 '14 at 10:33
51

Not sure exactly what you mean by "add one and select it", since it will be selected by default anyway. But, if you were to add more than one, it would make more sense. How about something like:

$('select').children().remove();
$('select').append('<option id="foo">foo</option>');
$('#foo').focus();

Response to "EDIT": Can you clarify what you mean by "This select box is populated by a set of radio buttons"? A <select> element cannot (legally) contain <input type="radio"> elements.

Heemanshu Bhalla
  • 3,603
  • 1
  • 27
  • 53
Bobby Jack
  • 15,689
  • 15
  • 65
  • 97
28
$('#mySelect')
    .empty()
    .append('<option value="whatever">text</option>')
    .find('option:first')
    .attr("selected","selected")
;
Hayden Chambers
  • 747
  • 1
  • 8
  • 19
24

Just one line to remove all options from the select tag and after you can add any options then make second line to add options.

$('.ddlsl').empty();

$('.ddlsl').append(new Option('Select all', 'all'));

One more short way but didn't tried

$('.ddlsl').empty().append(new Option('Select all', 'all'));
Kaushik shrimali
  • 1,178
  • 8
  • 15
23
$("#control").html("<option selected=\"selected\">The Option...</option>");
jvarandas
  • 352
  • 2
  • 7
15

Thanks to the answers I received, I was able to create something like the following, which suits my needs. My question was somewhat ambiguous. Thanks for following up. My final problem was solved by including "selected" in the option that I wanted selected.

$(function() {
  $('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected
  $("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1
  // Bind click event to each radio button.
  $("input[name='myRadio']").bind("click",
                                  function() {
    switch(this.value) {
      case "1":
        $('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ;
        break ;
      case "2":
        $('#mySelect').find('option').remove() ;
        var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo
        var options = '' ;
        for (var i = 0; i < items.length; i++) {
          if (i==0) {
            options += '<option selected value="' + items[i] + '">' + items[i] + '</option>';
          }
          else {
            options += '<option value="' + items[i] + '">' + items[i] + '</option>';
          }
        }
        $('#mySelect').html(options);   // Populate select box with array
        break ;
    } // Switch end
  } // Bind function end
                                 ); // bind end
}); // Event listener end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>One<input  name="myRadio" type="radio" value="1"  /></label>
<label>Two<input name="myRadio"  type="radio" value="2" /></label>
<select id="mySelect" size="9"></select>
Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
Jay Corbett
  • 28,091
  • 21
  • 57
  • 74
10

I've found on the net something like below. With a thousands of options like in my situation this is a lot faster than .empty() or .find().remove() from jQuery.

var ClearOptionsFast = function(id) {
    var selectObj = document.getElementById(id);
    var selectParentNode = selectObj.parentNode;
    var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
    selectParentNode.replaceChild(newSelectObj, selectObj);
    return newSelectObj;
}

More info here.

marioosh
  • 27,328
  • 49
  • 143
  • 192
9
$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');

The first line of code will remove all the options of a select box as no option find criteria has been mentioned.

The second line of code will add the Option with the specified value("testValue") and Text("TestText").

Devkinandan Chauhan
  • 1,785
  • 1
  • 17
  • 42
  • While this may answer the question, it would be a lot more useful if you provided an explanation as to *how* it answers it. – Nick Oct 12 '18 at 10:36
8

How about just changing the html to new data.

$('#mySelect').html('<option value="whatever">text</option>');

Another example:

$('#mySelect').html('
    <option value="1" selected>text1</option>
    <option value="2">text2</option>
    <option value="3" disabled>text3</option>
');
Shiv
  • 1,211
  • 4
  • 14
  • 24
8

Building on mauretto's answer, this is a little easier to read and understand:

$('#mySelect').find('option').not(':first').remove();

To remove all the options except one with a specific value, you can use this:

$('#mySelect').find('option').not('[value=123]').remove();

This would be better if the option to be added was already there.

humbads
  • 3,252
  • 1
  • 27
  • 22
8
  1. First clear all exisiting option execpt the first one(--Select--)

  2. Append new option values using loop one by one

    $('#ddlCustomer').find('option:not(:first)').remove();
    for (var i = 0; i < oResult.length; i++) {
       $("#ddlCustomer").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID));
    }
    
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Jaydeep Shil
  • 1,894
  • 22
  • 21
8

Another way:

$('#select').empty().append($('<option>').text('---------').attr('value',''));

Under this link, there are good practices https://api.jquery.com/select/

tuomastik
  • 4,559
  • 5
  • 36
  • 48
4

This will replace your existing mySelect with a new mySelect.

$('#mySelect').replaceWith('<Select id="mySelect" size="9">
   <option value="whatever" selected="selected" >text</option>
   </Select>');
Barun
  • 1,520
  • 2
  • 12
  • 18
4

Uses the jquery prop() to clear the selected option

$('#mySelect option:selected').prop('selected', false);
Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
mehrdad
  • 61
  • 1
4

You can do simply by replacing html

$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
Nadeem Manzoor
  • 760
  • 5
  • 14
4

I saw this code in Select2 - Clearing Selections

$('#mySelect').val(null).trigger('change');

This code works well with jQuery even without Select2

michael01angelo
  • 130
  • 2
  • 9
4

Cleaner give me Like it

   let data= []

   let inp = $('#mySelect')
        inp.empty()

        data.forEach(el=> inp.append(  new Option(el.Nombre, el.Id) ))
Carlos
  • 572
  • 1
  • 5
  • 13
3
  • save the option values to be appended in an object
  • clear existing options in the select tag
  • iterate the list object and append the contents to the intended select tag

var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};

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

$.each(listToAppend, function(val, text) {
    $('#selectID').append( new Option(text,val) );
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Nifemi Sola-Ojo
  • 851
  • 1
  • 9
  • 8
2

I used vanilla javascript

let select = document.getElementById("mySelect");
select.innerHTML = "";
Kazeem Quadri
  • 247
  • 3
  • 5
1

Hope it will work

$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
1
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
    var d = data[i];
    var option = $('<option/>').val(d.id).text(d.title);
    select.append(option);
}
select.val('');
-1

Try

mySelect.innerHTML = `<option selected value="whatever">text</option>`

function setOne() {
  console.log({mySelect});
  mySelect.innerHTML = `<option selected value="whatever">text</option>`;
}
<button onclick="setOne()" >set one</button>
<Select id="mySelect" size="9"> 
 <option value="1">old1</option>
 <option value="2">old2</option>
 <option value="3">old3</option>
</Select>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
-1

The shortest answer:

$('#mySelect option').remove().append('<option selected value="whatever">text</option>');
HJW
  • 342
  • 3
  • 13
-1

Try

$('#mySelect')
.html('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected");

OR

$('#mySelect').html('<option value="4">Value 4</option>
 <option value="5">Value 5</option>
<option value="6">Value 6</option>
<option value="7">Value 7</option>
<option value="8">Value 8</option>')
.find('option:first')
.prop("selected",true);
rsmdh
  • 128
  • 1
  • 2
  • 12