Determining which column / row is clicked by user

Using jQuery, I need to know if the user clicked the link or the third column, and I need to get the variable value in the first column. How to do it?

My html:

<div id="test"> <table id="tablex" cellpadding="0" cellspacing="0" border="0" class="display"> <thead> <tr> <th>Cod</th> <th>Name completo</th> <th>&nbsp;</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>John Foster 1</td> <td><img entity_id="1" class="image-selector" src='imagens/grid_cancel.png' title='' /></td> </tr> </tbody> </table> 

My jQuery:

 $("#tablex tbody").on("click", "td", function(event){ alert($(this).text()); }); 
+4
source share
3 answers
 $("#tablex tbody").on("click", "td", function(event){ alert($(this).index()); alert($(this).siblings("td:first").text()); }); 

$(this).index() will provide you with a zero column based index. $(this).siblings("td:first").text() will provide you with the text in the first column.

There is a fiddle here: http://jsfiddle.net/adrianonantua/EAEsG/

+4
source

This will give you the column number of the clicked column and the value of the 1st column ...

 $("#tablex tbody").on("click", "td", function(event){ var index = $(this).index(); var col1value = $(this).parent().find("td").first().text(); }); 
+2
source
  <script type="text/javascript"> $(document).ready(function() { $(".image-selector").on("click", function(event){ var colvalue = $(this).parent().parent().find("td").first().text(); alert(colvalue); }); }); </script> 

if you want it to be based on a TD click, not a click on an image, move the class to td instead of the image

HOWEVER is what I consider a cleaner alternative using HTML5 data attributes

HTML

  <td>1</td> <td>John Foster 1</td> <td><div data-value='1' class='image-selector'><img src='imagens/grid_cancel.png' title='' /></div></td> 

JQuery

  <script type="text/javascript"> $(document).ready(function() { $(".image-selector").on("click", function(event){ var colvalue = $(this).data('value'); alert(colvalue); }); }); </script> 
0
source

Source: https://habr.com/ru/post/1443288/


All Articles