views:

44

answers:

3

Hi, I have a table wherein the first column is a checkbox and the second one has a text. Whenever, the checkbox is checked, I want to know the corresponding value which is in the next cell. Please tell me how to do. If I use the getelementsbytagname function, it returns from the start of the document.

+1  A: 

Assuming you're using jQuery (or some other civilized framework), it's pretty easy:

$('table#yourTableId input:checkbox').click(function(ev) {
  if (this.checked) {
    // not sure what you mean by "want to know" ...
    console.log($(this).closest('tr').find('td:nth-child(2)').html());
  }
});

You could do it with the jQuery "live" event facility similarly, which'd be cheaper if there are a lot of checkboxes.

Pointy
A: 

The simplest way would be yo use jQuery or a similar library, that implements CSS3 selectors.

$('table input:checked').parent().parent().find('td.nth-child(2)').text():

You could also bind onto the change events of the checkboxes

$('input:checkbox').change = function(){
    val = $(this).parent().parent().find('td.nth-child(2)').text():
}
Matt
+1  A: 

This is quite simple to do without jquery. We have a input inside a td so we can go up a level and get the next sibling:

var nextTd = myInput.parentNode.nextSibling;

Because some browser insert empty text nodes between tds we can do the following to make sure we're on the right node:

if (nextTd.tagName != "TD")
    nextTd = nextTd.nextSibling;

Also, FWIW, getElementsByTagName can be called from any Node. Thus, if I have a table, I can call

myTable.getElementsByTagName("tr");

To return all rows inside of myTable.

Joel Potter