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 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
selectedIndexproperty 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:However, since one option may have the selected attribtue or otherwise be set to the default selected option, you may need to do:
And beware of setting attributes rather than properties, they have different effects in different browsers.