jQuery - Selector for duplicate ID's

Viewed 17732

I have a page with duplicate ID's for a form element. The catch is I the elements show up separately based on a toggle. So both ID's never show up simultaneously.

However when I do form validation on that element, it always selects the element displayed last in the code (even if its hidden).

Is there a selector to select the visible duplicate ID?

I've tried the following but to no avail:

$('#my_element:visible').val();
9 Answers

You can not specify using the # id selector only, you need to be more specific. One way is choose the type of element first then id:

For an input element:

$('input#my_element:visible').val();

or for a div element:

$('div#my_element:visible').val();

An alternative solution to select the element with jQuery and then get value from from the element directly:

$('#my_element:visible')[0].value
Related