开发者

How can I jump to the next cell in a table?

开发者 https://www.devze.com 2022-12-19 03:29 出处:网络
I have a table wherein the first column is a checkbox and the second one has a text. When开发者_Python百科ever, the checkbox is checked, I want to know the corresponding value which is in the next cel

I have a table wherein the first column is a checkbox and the second one has a text. When开发者_Python百科ever, 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.


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.


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.


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():
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号