Gonzalo
Gonzalo

Reputation: 355

jQuery selecting a dropdowns by name

I am having a problem to select a dropdown with a variable as name:

var dropDownOption = 2;
$([name='dropdownName'] option:eq("+ dropDownOption +")).attr('selected', true);

Where is the problem?

Thanks

Upvotes: 1

Views: 69

Answers (5)

PeterKA
PeterKA

Reputation: 24638

If the name of the drop down is a variable the selector would be as in the following line:

$('selecct[name=' + dropdownName + ']').children('option').eq( dropDownOption )
.prop( 'selected', true );  

If that was just shorthand then use:

$("select[name='dropdownName']").children('option').eq( dropDownOption )
.prop( 'selected', true );  

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

it should be this:

$("[name='dropdownName'] option:eq("+dropDownOption+")").attr('selected', 'selected');

or:

$("[name='dropdownName'] option:eq("+dropDownOption+")").prop('selected', true);

Upvotes: 1

Barmar
Barmar

Reputation: 780714

Your quotes are messed up, it should be:

$("[name='dropdownName'] option").eq(dropDownOption).attr('selected', true);

Upvotes: 0

Guffa
Guffa

Reputation: 700182

You are missing quotation marks around the string:

$("[name='dropdownName'] option:eq("+ dropDownOption +")").prop('selected', true);

You can also use the eq method:

$("[name='dropdownName'] option").eq(dropDownOption).prop('selected', true);

Unless you are using a multi-select, you can just set the selected index of the element:

$("[name='dropdownName']")[0].selectedIndex = dropDownOption;

Upvotes: 0

T J
T J

Reputation: 43156

You're missing quotes.

$("[name='dropdownName'] option:eq("+ dropDownOption +")").attr('selected', true);

Upvotes: 0

Related Questions