Raghav
Raghav

Reputation: 125

jQuery get closest DROPDOWN(SELECT) element with ID

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

Answers (3)

Dreen
Dreen

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

Neel
Neel

Reputation: 11741

You can use .prev as shown below

   $(this).prev().attr('value');

Upvotes: 0

Sid
Sid

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

Related Questions