How to set the first option on a select box using jQuery?
Something like this should do the trick: https://jsfiddle.net/TmJCE/898/
$('#name2').change(function(){
$('#name').prop('selectedIndex',0);
});
$('#name').change(function(){
$('#name2').prop('selectedIndex',0);
});
If you just want to reset the select element to it's first position, the simplest way may be:
$('#name2').val('');
To reset all select elements in the document:
$('select').val('')
EDIT: To clarify as per a comment below, this resets the select element to its first blank entry and only if a blank entry exists in the list.
As pointed out by @PierredeLESPINAY in the comments, my original solution was incorrect - it would reset the dropdown to the topmost option, but only because the undefined
return value resolved to index 0.
Here's a correct solution, which takes the selected
property into account:
$('#name').change(function(){
$('#name2').val(function () {
return $(this).find('option').filter(function () {
return $(this).prop('defaultSelected');
}).val();
});
});
DEMO: http://jsfiddle.net/weg82/257/
Original answer - INCORRECT
In jQuery 1.6+ you need to use the .prop
method to get the default selection:
// Resets the name2 dropdown to its default value
$('#name2').val( $('#name2').prop('defaultSelected') );
To make it reset dynamically when the first dropdown changes, use the .change
event:
$('#name').change(function(){
$('#name2').val( $('#name2').prop('defaultSelected') );
});