Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How do you remove 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 accompanying.
<Select id="mySelect" size="9"> </Select>


Edit: The accompanying code was useful with fastening. In any case, (in Internet Explorer) .val('whatever') didn't choose the alternative that was added. (I utilized the equivalent 'esteem' in both .append and .val.)

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


.focus() was nearer, yet the alternative didn't seem chosen as it does with .selected= "true". Nothing isn't right with my current code - I am simply attempting 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: the selected answer was close to what I needed. This worked for me:

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

2 Answers

aashaykumar

$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;
RoliMishra
You can also try this

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

Login / Signup to Answer the Question.