Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery-Get the id of closest div?

Hi I have a Table with list of vehicle

 <table>
 <tr class="${(i % 2) == 0 ? 'odd' : 'even'}" id ="rows">
   <td>
      <div class="check_box_div">
       <div class="check_box_list">
         <g:checkBox id = "isActive_${i}" class="isActive" name="isActive"  value="${vehicleInstance?.isActive}" />
          <input type="hidden" value="${vehicleInstance?.id}" class="vehicleId" name="vehicleId" id="isActive_${i}_" />
        </div>
       <div class="display_image" id ="display_image_${i}"></div>
      </div>    
    </td>

  </tr>

table has got many rows I want to get the id of div where the class name is "display_image" for each row i tried to get it like

   $(".isActive").click(function() {
     var checkBox_id = $(this).attr("id");
     var checkbox = $('#'+checkBox_id);
     var div_id =$('#'+checkBox_id).closest("div").find(".display_image").attr("id"); // always returns div_id =display_image_0(div id of first row)

This is works for first row but for second row also it returns id of div of first row only what is the change i should make so that i will get the id of div on each row

like image 404
maaz Avatar asked Jun 23 '11 10:06

maaz


2 Answers

Go up until you find the row, and then down again to find the display image:

$('.isActive').click(function() {
    var div_id = $(this).closest('tr').find('.display_image').attr('id');
    // ...
});

Note that this doesn't depend on your original element's ID at all - just the layout of your elements within the DOM.

More optimal solutions are possible, but this one will work regardless of the relative positions of the .isActive and .display_image elements within each row.

like image 180
Alnitak Avatar answered Oct 20 '22 02:10

Alnitak


Try this.

 $(".isActive").click(function() {
 var div_id = $(this).parents(".check_box_list").next(".display_image").attr("id");
 }

I used parents rather than parent just in case you shift any of your markup around.

like image 44
James South Avatar answered Oct 20 '22 01:10

James South