Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset the Value of a Select Box

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?

like image 903
OneChillDude Avatar asked Oct 04 '12 23:10

OneChillDude


People also ask

How do I get the default value in the select box?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

How do you reset selection in HTML?

If you want to reset the whole form, just call the built-in JavaScript . reset() on the <form> element. Also <select> has a defaultSelected which could be used in the function to reset if you just want a single element reset - see stackoverflow.com/questions/2348042/…

How do I reset the Select option in react?

By clicking on the clear icon which is shown in DropDownList element, you can clear the selected item in DropDownList through interaction.


8 Answers

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.

like image 64
RobG Avatar answered Oct 14 '22 02:10

RobG


This works for me:

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

FIDDLE

like image 44
Barmar Avatar answered Oct 14 '22 02:10

Barmar


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

like image 22
neRok Avatar answered Oct 14 '22 03:10

neRok


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.

like image 37
AndyLovesRuby Avatar answered Oct 14 '22 02:10

AndyLovesRuby


use the .val('') setter

jsfiddle example

$('select').val('1');
like image 34
MikeM Avatar answered Oct 14 '22 02:10

MikeM


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;
  });
};
like image 45
Hristo Avatar answered Oct 14 '22 02:10

Hristo


What worked for me was:

$('select option').each(function(){$(this).removeAttr('selected');});   
like image 23
ORCA Project Avatar answered Oct 14 '22 03:10

ORCA Project


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.

like image 37
Bibek Oli Avatar answered Oct 14 '22 02:10

Bibek Oli