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..
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.
This will replace your existing mySelect with a new mySelect.
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:
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?
Building on mauretto's answer, this is a little easier to read and understand:
To remove all the options except one with a specific value, you can use this:
This would be better if the option to be added was already there.