[javascript] How do you remove all the options of a select box and then add one option and select it with jQuery?

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..

This question is related to javascript jquery html-select option dynamic-html

The answer is


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

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

Uses the jquery prop() to clear the selected option

$('#mySelect option:selected').prop('selected', false);

$("#control").html("<option selected=\"selected\">The Option...</option>");

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();

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>');

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('');

You can do simply by replacing html

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

I saw this code in Select2 - Clearing Selections

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

This code works well with jQuery even without Select2


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;

Hope it will work

$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));

Another way:

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

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


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.


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>
');

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

Try

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

_x000D_
_x000D_
function setOne() {
  console.log({mySelect});
  mySelect.innerHTML = `<option selected value="whatever">text</option>`;
}
_x000D_
<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>
_x000D_
_x000D_
_x000D_


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.


$("#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").


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'));

  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));
    }
    

  • 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

_x000D_
_x000D_
var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};_x000D_
_x000D_
$('#selectID').empty();_x000D_
_x000D_
$.each(listToAppend, function(val, text) {_x000D_
    $('#selectID').append( new Option(text,val) );_x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


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.

_x000D_
_x000D_
$(function() {_x000D_
  $('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected_x000D_
  $("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1_x000D_
  // Bind click event to each radio button._x000D_
  $("input[name='myRadio']").bind("click",_x000D_
                                  function() {_x000D_
    switch(this.value) {_x000D_
      case "1":_x000D_
        $('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ;_x000D_
        break ;_x000D_
      case "2":_x000D_
        $('#mySelect').find('option').remove() ;_x000D_
        var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo_x000D_
        var options = '' ;_x000D_
        for (var i = 0; i < items.length; i++) {_x000D_
          if (i==0) {_x000D_
            options += '<option selected value="' + items[i] + '">' + items[i] + '</option>';_x000D_
          }_x000D_
          else {_x000D_
            options += '<option value="' + items[i] + '">' + items[i] + '</option>';_x000D_
          }_x000D_
        }_x000D_
        $('#mySelect').html(options);   // Populate select box with array_x000D_
        break ;_x000D_
    } // Switch end_x000D_
  } // Bind function end_x000D_
                                 ); // bind end_x000D_
}); // Event listener end
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>One<input  name="myRadio" type="radio" value="1"  /></label>_x000D_
<label>Two<input name="myRadio"  type="radio" value="2" /></label>_x000D_
<select id="mySelect" size="9"></select>
_x000D_
_x000D_
_x000D_


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.


why not just use plain javascript?

document.getElementById("selectID").options.length = 0;

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html-select

How can I get new selection in "select" in Angular 2? How to show disable HTML select option in by default? Remove Select arrow on IE Bootstrap 3 select input form inline Change <select>'s option and trigger events with JavaScript How to use a Bootstrap 3 glyphicon in an html select Creating a select box with a search option Drop Down Menu/Text Field in one How to have a default option in Angular.js select box How to set the 'selected option' of a select dropdown list with jquery

Examples related to option

Get Selected value from dropdown using JavaScript html select option SELECTED How to check if an option is selected? JQuery refresh select box android: changing option menu items programmatically How to implement the --verbose or -v option into a script? set option "selected" attribute from dynamic created option How to preSelect an html dropdown list with php? jQuery remove selected option from this using href links inside <option> tag

Examples related to dynamic-html

How do you remove all the options of a select box and then add one option and select it with jQuery?