admin管理员组

文章数量:1136548

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?

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?

Share Improve this question edited Oct 5, 2012 at 3:22 OneChillDude asked Oct 4, 2012 at 23:39 OneChillDudeOneChillDude 8,00610 gold badges42 silver badges81 bronze badges 5
  • Have you tried to reset using "val()"? – rafaelbiten Commented Oct 4, 2012 at 23:41
  • Um ... your code works for me. – McGarnagle Commented Oct 4, 2012 at 23:46
  • You should code find('option:eq(0)') instead of find('option :eq(0)') – Ram Commented Oct 4, 2012 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 Commented Oct 5, 2012 at 1:46
  • Click here to see my answer on this subject or visit: stackoverflow.com/a/46196428/6016078 – Jean Douglas Commented Sep 13, 2017 at 11:40
Add a comment  | 

9 Answers 9

Reset to default 72

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.

This works for me:

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

FIDDLE

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.

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

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.

use the .val('') setter

jsfiddle example

$('select').val('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;
  });
};

What worked for me was:

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

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');

本文标签: javascriptReset the Value of a Select BoxStack Overflow