Kleber S.
Kleber S.

Reputation: 8240

JS: get the closest id number

Having the following structure:

<td class="padding_right padding_left">Neighborhood</td>
<td>
    <div id="neighborhoods_region">    
    <select class="inputs_form_data" id="neighborhood_id2" name="neighborhood_id2">
        <option value=""></option>
        <option value=""></option>
    </select>
    </div>
</td>
<td width="10%"><a class='delete-region'>remover</a></td>​

I'm trying to when the remove link is clicked, to get the id number of the select id. In this case, I need to get the number 2 from the "neighborhood_id2".

But first I just trying to get the full id. neighborhood_id2 with the following code:

$(document.body).on('click','a.delete-region', function () {
    alert($(this).closest('select').attr("id"));
});

but this returns me undefined.

note: the id number is generated on-the-fly on a dynamic form. So I may have neighborhood_id3 and so on.

Upvotes: 2

Views: 137

Answers (1)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try using .closest('tr') which will get you the tr and then find the select,

alert($(this).closest('tr').find('select').attr("id"));

As Andreas pointed out.. use .on (delegated events) / .delegate

Upvotes: 6

Related Questions