Reset select value to default

html, javascript, jquery

Solution

You can make use of the `defaultSelected` property of an option element:

Contains the initial value of the `selected` HTML attribute, indicating whether the option is selected by default or not.

So, the DOM interface already keeps track which option was selected initially.

$("#reset").on("click", function () {
    $('#my_select option').prop('selected', function() {
        return this.defaultSelected;
    });
});

DEMO

This would even work for multi-select elements.

If you don't want to iterate over all options, but "break" after you found the originally selected one, you can use `.each` instead:

$('#my_select option').each(function () {
    if (this.defaultSelected) {
        this.selected = true;
        return false;
    }
});

Without jQuery:

var options = document.querySelectorAll('#my_select option');
for (var i = 0, l = options.length; i < l; i++) {
    options[i].selected = options[i].defaultSelected;
}

Problem

I have select box ``` <select id="my_select"> <option value="a">a</option> <option value="b" selected="selected">b</option> <option value="c">c</option> </select> <div id="reset"> reset </div> ``` I have also reset button, here default (selected) value is "b", suppose I select "c" and after I need resert select box value to default, how to make this using jquery? ``` $("#reset").on("click", function () { // What do here? }); ``` jsfiddle: http://jsfiddle.net/T8sCf/1/

Original source

Related problems