cybertextron
cybertextron

Reputation: 10981

retrieving the cell / column value with JQuery / JavaScript

I have this following Table, which utilizes Google Visualization API:

<html>
  <head>
    <script type='text/javascript' src='https://www.google.com/jsapi'></script>
    <script type='text/javascript'>
      google.load('visualization', '1', {packages:['table']});
      google.setOnLoadCallback(drawTable);
      function drawTable() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('number', 'Salary');
        data.addColumn('boolean', 'Full Time Employee');
        data.addRows([
          ['Mike',  {v: 10000, f: '$10,000'}, true],
          ['Jim',   {v:8000,   f: '$8,000'},  false],
          ['Alice', {v: 12500, f: '$12,500'}, true],
          ['Bob',   {v: 7000,  f: '$7,000'},  true]
        ]);

        var table = new google.visualization.Table(document.getElementById('table_div'));
        table.draw(data, {showRowNumber: true});
      }
    </script>
  </head>

  <body>
    <div id='table_div'></div>
  </body>
</html>

What would I like to know is how to, when I click in a cell:

  1. Return the Column Index in which that cell is located ?
  2. Return the name of the column's header ?
  3. How to return that specifically cell's value ?

If I figure out how to do at least one of those, then my problem will be solved. It has dodged me a lot. Thanks

Upvotes: 1

Views: 312

Answers (2)

iambriansreed
iambriansreed

Reputation: 22261

Proof: http://jsfiddle.net/iambriansreed/43yAy/

Retrieving via row / column:

var r = 1; // second row (zero based index)
var c = 2; // third column (zero based index)

$('#table_div tr:eq('+r+') td:eq('+c+')').text();

Clicking on TD:

$('#table_div').on('click', 'td', function(){    
    $(this).text();
});

Upvotes: 1

CoursesWeb
CoursesWeb

Reputation: 4237

Here is a way to get the value of the clicked cell (with jQuery).

<body>
<div id='table_div'></div>
<script>
function getTD() {
  $('#table_div td').click(function(){
    var val = $(this).html();
    alert(val);
  });
}
setTimeout('getTD()', 2000);
</script>
</body>

It is used setTimeout() to be sure that the table is added when the jQuery code is executed.

Upvotes: 0

Related Questions