4

Using JQuery, I need to know if the User clicked on the link or third column, and need to get the value of the variable in the first column. How do I do this?

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());
});
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
user1789239
  • 87
  • 1
  • 6

3 Answers3

5
$("#tablex tbody").on("click", "td", function(event){
    alert($(this).index());
    alert($(this).siblings("td:first").text());
});

$(this).index() will give you the zero-based index of the clicked column. $(this).siblings("td:first").text() will give you the text in the first column.

Here, have a fiddle: http://jsfiddle.net/adrianonantua/EAEsG/

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
  • 1
    the siblings method will return the first sibling in the collection.. so if you click on the first column.. you will get the second column. It's better if you traverse back to the row then get first td – wirey00 Oct 31 '12 at 17:58
3

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();
});
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
0
 <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 the TD click rather than the image click, move the class to the td instead of the image

HOWEVER here 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> 
Jay Rizzi
  • 4,196
  • 5
  • 42
  • 71