Home > other >  Reset selected value from dropdown using jQuery
Reset selected value from dropdown using jQuery

Time:01-02

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.

CodePudding user response:

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 an each() loop:

$("#cityCode, #townCode").each((i, el) => el.selectedIndex = 0);

Alternatively, if the first option in both dropdowns has an empty value, eg. <option value="">Please select</option>, then you can use the val() method which will implicitly loop for you:

$("#cityCode, #townCode").val('');

CodePudding user response:

Use jQuery's .prop() method:

Set the selected option to 0 index

$("#cityCode, #townCode").prop("selectedIndex", 0);
<select id="cityCode">
  <option>111<option>
  <option selected>222<option>
  <option>333<option>
</select>

<select id="townCode">
  <option>aaa<option>
  <option selected>bbb<option>
  <option>ccc<option>
</select>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

Reset option to original defaultSelected index

Notice that the above sets specifically the index to 0 (first option element), which might not be the original defaultSelected.

To account for this use:

$("#cityCode").val("333"); // just to force emulate some dynamic change
$("#townCode").val("ccc");

$("#cityCode, #townCode").prop("selectedIndex", function() {
  const idx = [...this.options].findIndex((opt) => opt.defaultSelected);
  return idx < 0 ? 0 : idx;
});
<select id="cityCode">
  <option>111<option>
  <option selected>222<option>
  <option>333<option>
</select>

<select id="townCode">
  <option>aaa<option>
  <option selected>bbb<option>
  <option>ccc<option>
</select>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

Reset form

If instead, you wish to reset the entire form use:

$("#someForm")[0].reset();

CodePudding user response:

Try this:

  $("#cityCode, #townCode").each(function(){
                    $(this).selectedIndex = 0;
                });
  • Related