Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 727
Jay Corbett Avatar asked Sep 06 '08 20:09

Jay Corbett


People also ask

How remove all option from select tag in jQuery?

To remove all options from a select list using jQuery, the simplest way is to use the empty() method.

How do you remove all options from select in jQuery except first?

Explanation: If we want to remove all items from dropdown except the first item then we can use $('#ddlItems option:not(:first)'). remove(); Here we have excluded first item from being deleted. If we want to remove all items from dropdown except the last item then we can use $('#ddlItems option:not(:last)').

How do I remove selected option from select?

The option to be removed is selected by getting the select box. The value to be removed is specified on the value selector (value='optionValue') on the select box. The remove() method is then used to remove this selected option.


2 Answers

$('#mySelect')     .find('option')     .remove()     .end()     .append('<option value="whatever">text</option>')     .val('whatever') ; 
like image 111
Matt Avatar answered Sep 20 '22 11:09

Matt


$('#mySelect')     .empty()     .append('<option selected="selected" value="whatever">text</option>') ; 
like image 25
Mahzilla Avatar answered Sep 22 '22 11:09

Mahzilla