I am trying to clear selected value on a button click using jQuery.
$("#cityCode")[0].selectedIndex = 0;
This is working fine for a single selector, but if I target multiple selectors like this
$("#cityCode, #townCode")[0].selectedIndex = 0;
It works only for first ID. Can anyone help me to write fix syntax?
To clear all selected options from dropdown on a button click.
3
Answers
As you’re selecting multiple elements you need to reset the
selectedIndex
on all of them, not the 0th element. To do that you can use aneach()
loop:Alternatively, if the first option in both dropdowns has an empty value, eg.
<option value="">Please select</option>
, then you can use theval()
method which will implicitly loop for you:Try this:
Use jQuery’s .prop() method:
Set the selected option to
0
indexThis is considered bad practice since the
defaultSelected
might not necessarily be the option at index0
. Such depends on which option had originally theselected
HTML attribute set (see the other example). This is only OK -ish if you don’t use such attribute on your Option elements.In vanilla JavaScript:
Reset option to original defaultSelected index
Notice that the above sets specifically the index to
0
(first option element), which might not be the originaldefaultSelected
.To account for this use:
Reset form
If instead, you wish to reset the entire form use:
Don’t use
.val("")
as suggested in other answers… don’t use
.val("")
. Here’s why: