49

I'm trying to reset the value of two select fields, structured like this,

<select>
  <option></option>
  <option></option>
  <option></option>
</select>

<select>
  <option></option>
  <option></option>
  <option></option>
</select>

jQuery,

$('select').each(function(idx, sel) {
  $(sel).find('option :eq(0)').attr('selected', true);
});

Unfortunately, no matter how many ways I try it, it just doesn't happen. Nothing in the console. I have no idea what's going on? I know there has to be a way to do this, you can do anything with JS

EDIT:

I figured out that the issue only occurs when I try to fire the code on the click of a dom element, however, I know that the code should be working, because when I have

$('p').click(function(){
  console.log('test');
});

It outputs 'test' to the console, but when I include the code in this function, nothing happens. Why is this?

OneChillDude
  • 7,856
  • 10
  • 40
  • 79
  • Have you tried to reset using "val()"? – rafaelbiten Oct 04 '12 at 23:41
  • Um ... your code works for me. – McGarnagle Oct 04 '12 at 23:46
  • You should code `find('option:eq(0)')` instead of `find('option :eq(0)')` – Ram Oct 04 '12 at 23:47
  • That code will set the selected attribute of the first option of each select. It will not remove the selected attribute from other options that might have it (so two options might then have the selected attribute, which might have unexpected results in multiple select elements). Also, it will not necessarily make the option selected, since the selected attribute only sets which option is selected by default, not which one is currently selected. Some browsers do make it the currently selected option, others don't. – RobG Oct 05 '12 at 01:46
  • Click [here](https://stackoverflow.com/a/46196428/6016078) to see my answer on this subject or visit: https://stackoverflow.com/a/46196428/6016078 – Jean Douglas Sep 13 '17 at 11:40

9 Answers9

70

I presume you only want to reset a single element. Resetting an entire form is simple: call its reset method.

The easiest way to "reset" a select element is to set its selectedIndex property to the default value. If you know that no option is the default selected option, just set the select elemen'ts selectedIndex property to an appropriate value:

function resetSelectElement(selectElement) {
    selecElement.selectedIndex = 0;  // first option is selected, or
                                     // -1 for no option selected
}

However, since one option may have the selected attribtue or otherwise be set to the default selected option, you may need to do:

function resetSelectElement(selectElement) {
    var options = selectElement.options;

    // Look for a default selected option
    for (var i=0, iLen=options.length; i<iLen; i++) {

        if (options[i].defaultSelected) {
            selectElement.selectedIndex = i;
            return;
        }
    }

    // If no option is the default, select first or none as appropriate
    selectElement.selectedIndex = 0; // or -1 for no option selected
}

And beware of setting attributes rather than properties, they have different effects in different browsers.

RobG
  • 142,382
  • 31
  • 172
  • 209
30

This works for me:

$('select').prop('selectedIndex', 0);

FIDDLE

Barmar
  • 741,623
  • 53
  • 500
  • 612
11

neRok touched on this answer above and I'm just expanding on it.

According to the slightly dated, but handy O'Reilly reference book, Javascript: The Definitive Guide:

The selectedIndex property of the Select object is an integer that specifies the index of the selected option within the Select object. If no option is selected, selectedIndex is -1.

As such, the following javascript code will "reset" the Select object to no options selected:

select_box = document.getElementById("myselectbox");
select_box.selectedIndex = -1;

Note that changing the selection in this way does not trigger the onchange() event handler.

AndyLovesRuby
  • 153
  • 1
  • 4
9

Further to @RobG's pure / vanilla javascript answer, you can reset to the 'default' value with

selectElement.selectedIndex = null;

It seems -1 deselects all items, null selects the default item, and 0 or a positive number selects the corresponding index option.

Options in a select object are indexed in the order in which they are defined, starting with an index of 0.

source

neRok
  • 995
  • 9
  • 21
  • null isn't possible because [selectedIndex](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedIndex) is a number. Setting it to a `-1` is the only valid approach. Browsers may be handling null differently. – Matt Jensen Jun 28 '23 at 16:15
1

use the .val('') setter

jsfiddle example

$('select').val('1');
MikeM
  • 27,227
  • 4
  • 64
  • 80
1

I found a little utility function a while back and I've been using it for resetting my form elements ever since (source: http://www.learningjquery.com/2007/08/clearing-form-data):

function clearForm(form) {
  // iterate over all of the inputs for the given form element
  $(':input', form).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase(); // normalize case
    // it's ok to reset the value attr of text inputs, 
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared 
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

... or as a jQuery plugin...

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};
Hristo
  • 45,559
  • 65
  • 163
  • 230
  • Why would you do that instead of simply `form.reset()`? Particularly as the above ignores default values. – RobG Oct 05 '12 at 01:37
  • I guess I was going more of the "clear form" approach than the "reset form" approach. I'm not sure which the user is looking for... – Hristo Oct 05 '12 at 01:49
1

What worked for me was:

$('select option').each(function(){$(this).removeAttr('selected');});   
1

The easiest method without using javaScript is to put all your <select> dropdown inside a <form> tag and use form reset button. Example:

<form>
  <select>
    <option>one</option>
    <option>two</option>
    <option selected>three</option>
  </select>
  <input type="reset" value="Reset" />
</form>

Or, using JavaScript, it can be done in following way:

HTML and JS Code:

const button = document.getElementById('revert');
const options = document.querySelectorAll('select option');
button.onclick = () => {
  for (var i = 0; i < options.length; i++) {
    options[i].selected = options[i].defaultSelected;
  }
}
<select>
  <option selected>one</option>
  <option>two</option>
  <option>three</option>
</select>
<button id="revert">Reset</button>

Both of these methods will work if you have multiple selected items or single selected item.

Teocci
  • 7,189
  • 1
  • 50
  • 48
Bibek Oli
  • 366
  • 2
  • 14
0

for select2

$('select').select2().val('').trigger('change');

and if you want reset just select2 elements in your form

$("#formId").find('select').select2().val('').trigger('change');
Omid.Hanjani
  • 1,444
  • 2
  • 20
  • 29