user1431218
user1431218

Reputation: 13

Using jQuery to set multiple selects using each

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

Answers (6)

C.S.
C.S.

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

thecodeparadox
thecodeparadox

Reputation: 87073

$("option:first", ".myselect").prop('selected', true);

Working sample

Upvotes: 0

aziz punjani
aziz punjani

Reputation: 25776

You don't need to use each. Here's an example.

​$('.select').find('option:first').prop('selected', true );

Upvotes: 0

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

Do it like this:

$('.myclass').each(function() {
    $(this).find('option:first').attr('selected','selected');
});

Upvotes: 1

VisioN
VisioN

Reputation: 145378

How about this short one?

​$(".myclass :first-child").prop("selected", true);​​​​​​​​​

DEMO: http://jsfiddle.net/u8S54/

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try like below,

$('.myclass').each(function() {
   this.selectedIndex = 0;
});

DEMO: http://jsfiddle.net/ZDYjP/

Upvotes: 2

Related Questions