Reputation: 13
I have a page full of selects, and they all have a common class. I need to set every one of them to their first option. Easy, right? But what I finally wound up getting to work feels like such a hack... is there a better way?
$('.myclass').each(function() {
var firstOptSelector = '#' + $(this).attr('id') + ' option:first'; // HACK
$(firstOptSelector).attr('selected','selected');
});
Upvotes: 1
Views: 66
Reputation: 422
If you remove the selected property then the first one by default is what is shown.
$('.myclass').find('option:selected').removeAttr("selected");
Upvotes: 0
Reputation: 25776
You don't need to use each. Here's an example.
$('.select').find('option:first').prop('selected', true );
Upvotes: 0
Reputation: 13461
Do it like this:
$('.myclass').each(function() {
$(this).find('option:first').attr('selected','selected');
});
Upvotes: 1
Reputation: 145378
How about this short one?
$(".myclass :first-child").prop("selected", true);
DEMO: http://jsfiddle.net/u8S54/
Upvotes: 2
Reputation: 79830
Try like below,
$('.myclass').each(function() {
this.selectedIndex = 0;
});
DEMO: http://jsfiddle.net/ZDYjP/
Upvotes: 2