sstauross
sstauross

Reputation: 2680

Get the value of a tables's cell depending on the x and y coordinates

as i am new to jQuery i would like to ask the following, i have a table like this:

<table id="lettersGrid" border="1">
 <tr>
  <td>..</td>
  <td>..</td>
  <td>..</td>
 </tr>
 <tr>
  <td>..</td>
  <td>..</td>
  <td>..</td>
 </tr>
 </table>

i want to use jQuery to get the value of a specific cell depending on the x and y position of it, so i have

$("td").mouseover(function(){
 x=this.parentNode.rowIndex;    //get the x coordinate of the cell 
 y=this.cellIndex;      //get the y coordinate of the cell

 //??whats next??
});

any help?

Upvotes: 3

Views: 4179

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206467

DEMO fiddle

$("button").click(function() {
    var row = $('input.enterRow').val()- 1;    // -1 CAUSE .eq() IS zero BASED
    var cell = $('input.enterCell').val()- 1;
    var value = $('#lettersGrid tr:eq(' + row + ') >td:eq(' + cell + ')').html();

    $('.result').html( value );               // PRINT VALUE
});

Upvotes: 0

sstauross
sstauross

Reputation: 2680

i had told it at a comment before but just to be clear enough for someone with the same problem,i have found something really interesting that solved my problem, it was that simple:

$('#lettersGrid tr:eq(1) td:eq(1)').html();to get the element at col=1 row=1 starting from 0

or

$('#lettersGrid tr:nth-child(1) td:nth-child(1)').html(); to get the element at col=1 row=1 starting from 1

Upvotes: 0

BonyT
BonyT

Reputation: 10940

If all you want is the content of the cell that you are "mouseing-over"

 $('td').mouseover(function(){
     var content = $(this).html();
     //do whatever you like with the content....
 });

Edited: Use the index function to get the col/row values

 $('td').mouseover(function(){
     col = $(this).parent().children().index($(this));
     row = $(this).parent().parent().children().index($(this).parent());
 });

To Select similar rows:

 $('table tr').eq(row).find('td');

To Select similar cols:

 $('table tr').each(function() {
    $(this).find('td').eq(col);
 }

To find the value of a specific row + col

 $('table tr').eq(row).find('td').eq(col).html();

Upvotes: 1

Related Questions