Charles Morin
Charles Morin

Reputation: 1447

How to select a specific option in a dropdown that has multiple instances?

Here is a basic example of what I am trying to achieve :

<select name="userId" id="userId">
<option value="1">Charles</option>
<option value="2">Mike</option>
<option value="3">Jeff</option>
<option value="4">Kevin</option>
</select>

<select name="userId" id="userId">
<option value="1">Charles</option>
<option value="2">Mike</option>
<option value="3">Jeff</option>
<option value="4">Kevin</option>
</select>

<select name="userId" id="userId">
<option value="1">Charles</option>
<option value="2">Mike</option>
<option value="3">Jeff</option>
<option value="4">Kevin</option>
</select>

For instance, I would like to select the third option (Jeff) of the second "userId" dropdown. I know how to do that for a unique dropdown, but I can't get it to work with multiple dropdowns having the same ID.

I thought I would be able to do it with the following line:

$("input[id=userId]").eq(1).val("3");

.. but it doesn't work.

Any idea?

Thank you very much

Charles

Upvotes: 0

Views: 249

Answers (1)

Irongaze.com
Irongaze.com

Reputation: 1645

You can't. A DOM element's id is supposed to be globally unique. Having the same id="userId" bit 3 times is broken HTML. Instead, use:

<select name="userId" class="userId">
...
</select>

Then you can do:

$('select.userId').<whatever jquery you want>;

and you'll be all set.

Upvotes: 1

Related Questions