Reputation: 125
Hi All I am trying to get the closest dropdown element with a Id on it, On a page I am having 2 elements with same Id attribute, now I want to select the closest one when I click any element in the page
<select id="XYZ" .... >
<bla bla bla OTHER DOM ELEMENTS>
<select id="XYZ" ... >
<bla bla bla OTHER DOM ELEMENTS>
<btn="ABC" />
when I click the button I want to get the VALUE of the closest SELECT element
Thanks in advance for the help
Upvotes: 0
Views: 1252
Reputation: 7226
You really should not have two elements with the same ID on one page, since it is against the HTML specification and can cause problems.
Instead, consider using a class and separate IDs if necessary, and selecting with jQuery:
<select class="XYZ" id="select_1" .... >
<bla bla bla OTHER DOM ELEMENTS>
<select class="XYZ id="select_2" ... >
<bla bla bla OTHER DOM ELEMENTS>
<button id="ABC" />
<script>
$(function()
{
$('#ABC').click(function()
{
var value = $('#select_2').val();
});
});
</script>
Upvotes: 1
Reputation: 801
Don't use Id user class instead and then find closest element, jquery will not work properly when there will be more then one element with same id.
and in your html parent and child element are looking like at same level if so then use siblings instead of closest.
Upvotes: 0