OneChillDude OneChillDude - 3 months ago 20
Javascript Question

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?

Answer

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.