Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  146] [ 5]  / answers: 1 / hits: 167705  / 12 Years ago, thu, october 4, 2012, 12:00:00

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?


More From » jquery

 Answers
64

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.


[#82748] Wednesday, October 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
meadowe

Total Points: 0
Total Questions: 97
Total Answers: 97

Location: Laos
Member since Fri, Sep 11, 2020
4 Years ago
meadowe questions
Thu, Aug 5, 21, 00:00, 3 Years ago
Thu, Jul 9, 20, 00:00, 4 Years ago
Mon, Jun 8, 20, 00:00, 4 Years ago
Sun, Feb 9, 20, 00:00, 4 Years ago
;