views:

49

answers:

3

Hi all

I have a HTML table like below:

ColA       ColB  ColC ColD ColE ColF
Checked    AAAA  BBBB CCCC DDDD EEEE
Unchecked  AAAA  BBBB CCCC DDDD EEEE
Checked    AAAA  BBBB CCCC DDDD EEEE
Checked    AAAA  BBBB CCCC DDDD EEEE
Unchecked  AAAA  BBBB CCCC DDDD EEEE
Checked    AAAA  BBBB CCCC DDDD EEEE
Checked    AAAA  BBBB CCCC DDDD EEEE

ColA is a Check box. I want to get the ColD value of all rows whose ColA is Checked. I want to use the jquery to do it. Does anyone meet it before?

Best Regards,

A: 

The no-jQuery solution

var inputs = document.getElementById("tableId").getElementsByTagName("input"), input, i = inputs.length;
while (i--){
    input = inputs[i];
    if (input.type == "checkbox" && input.checked){
         console.log(input.parentNode.parentNode.childNodes[3].innerHTML);
    }
}

This is guaranteed to be a lot faster than any of the css-selector methods (and easier to understand).

And a slight rewrite to return an array

var array_of_values = (function(table){
    var values = [], inputs = table.getElementsByTagName("input"), i = inputs.length;
    while (i--) 
        if (inputs[i].type == "checkbox" && inputs[i].checked) 
            values.push(inputs[i].parentNode.parentNode.childNodes[3].innerHTML);
    return values;
})(document.getElementById("tableId"));
Sean Kinsey
question was explicitly bound to jQuery
jAndy
Thats really not a good argument.. Especially since most in here think that javascript == jQuery..
Sean Kinsey
I would not expect to get eggs if I ask for oranges
jAndy
appeal to ridicule.He asked for neither - he wanted to hit a nail with a clunky sledge when he had a hammer.
Sean Kinsey
Have to agree with jAndy here - jQuery solution lot less code therefore easier to understand, also less prone to breaking when making changes.
James Westgate
I'm not fighting that :) But I hate to cater to those who treats jQuery as the 'one and only' - so I offer alternatives that are not bound to any framework. As a sidenote: if you break your code when making changes.. well, then you do not know what you are doing..
Sean Kinsey
thanks you all. Actually, I just want to use the JavaScript. The reason that I bind it to jquery is that it's easier. If non-jquery can also solve this problem, it's also great.
Yongwei Xing
+4  A: 
var array_of_the_values = $('table input:checked').map(function() { 
    return $(this).parents('tr').find('td:eq(3)').text();
  }).get();
kkyy
Actually, I want to do a minor modification. I can not get the right answer using your code. So I make a little change, I change the parents('tr') to parent().parent()
Yongwei Xing
A: 

$('table input:checked').parent('tr').find('td:eq(3)').text();

ljubomir