Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Selecting Table Rows with Checkbox

I have a table as

<table id="rowclick2">
  <tbody>
    <tr >
      <td class="cb"><input type="checkbox" value="yes"></td>
      <td>row 1</td>
       <td>A</td>
    </tr>    
    <tr >
      <td class="cb"><input type="checkbox" value="yes" ></td>
      <td>row 2</td>
       <td>B</td>
    </tr>    
    <tr>
      <td class="cb"><input type="checkbox" value="yes"></td>
      <td>row 3</td>
      <td>C</td>  
    </tr>    
  </tbody>
</table>

where I want to get each cell (when the button is clicked) in a row whose checkboxes are checked

I tried filter

  $('#test').click(function(){

      $('#rowclick2 tr').filter(':has(:checkbox:checked)').each(
          //get row values
      );
    });

It's pretty simple yet I can't see what I am missing...

Here is the jsfiddle link...

like image 685
add9 Avatar asked Mar 25 '11 08:03

add9


People also ask

How can check checkbox in TD using jquery?

You can do this: var isChecked = $("#rowId input:checkbox")[0]. checked; That uses a descendant selector for the checkbox, then gets the raw DOM element, and looks at its checked property.

What is checked in JavaScript?

The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.


2 Answers

You're almost there :)

If you want all <td> s in rows where the checkbox is checked:

$('#rowclick2 tr').filter(':has(:checkbox:checked)').find('td');

E.g.:

$('#rowclick2 tr').filter(':has(:checkbox:checked)').find('td').each(function() {
    // this = td element
});

More elaborate example is on JsFiddle.

BTW
The .filter(':has(:checkbox:checked)') can be written as .has(':checkbox:checked') if you, like me, find that easier to read.

like image 184
jensgram Avatar answered Oct 29 '22 08:10

jensgram


You can try this code:

$('#test').click(function(){

    $('td.cb:checked').parents('tr').each(
          //get row values
      );
}

HTH!

like image 21
SubniC Avatar answered Oct 29 '22 07:10

SubniC