Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get <td> values only in specific rows using jQuery

Tags:

jquery

loops

rows

I have a table (id="docsTable") whose rows look similar to this:

<tr bgcolor="#E7DDCC">
    <td align="center"><input type="checkbox" name="docsToAddToClass[]" value="35" /></td>
    <td>Document Title</td>
    <td>Document Description.</td>
</tr>

I need to iterate through the table, determine which checkboxes the user has checked, and for the rows with a checked checkbox, grab the value for the first and the text for the next two.

I don't need to build a collection: Within each iteration I want to change some elements elsewhere. That's not the hard part (for me). It's trying to figure out how to iterate through the table and select only the s with checked checkboxes.

like image 441
marky Avatar asked Dec 16 '22 13:12

marky


2 Answers

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" ></script>
    <script type="text/javascript">
        $(function(){
            $('#btnTest').click(function(){
                $('#docsTable input[type="checkbox"]:checked').each(function(){
                    var $row = $(this).parents('tr'); 
                    alert($row.find('td:eq(0) input').val());
                    alert($row.find('td:eq(1)').html());
                    alert($row.find('td:eq(2)').html());
                });
            });
        });
    </script>
  </head>
  <body>
    <table id="docsTable">
        <tr bgcolor="#E7DDCC">
            <td align="center"><input type="checkbox" name="docsToAddToClass[]" value="35" /></td>
            <td>Document Title 1</td>
            <td>Document Description.</td>
        </tr>
        <tr bgcolor="#E7DDCC">
            <td align="center"><input type="checkbox" name="docsToAddToClass[]" value="36" /></td>
            <td>Document Title 2</td>
            <td>Document Description.</td>
        </tr>
        <tr bgcolor="#E7DDCC">
            <td align="center"><input type="checkbox" name="docsToAddToClass[]" value="37" /></td>
            <td>Document Title 3</td>
            <td>Document Description.</td>
        </tr>
    </table>
    <input type='button' id='btnTest' value='Get Rows' />
  </body>
</html>   
like image 74
Brandon Boone Avatar answered Dec 24 '22 13:12

Brandon Boone


You can try something along this line:

$('tr > td:first-child > input:checked').each(function() {  
    // $(this).val() is the value of the input
    // $(this).parent().siblings() will refer to the two <td>'s  
    // You can also try other traversal methods like $(this).parent().next()
});  

Hope this works and helps!

like image 31
Marcelo Zabani Avatar answered Dec 24 '22 13:12

Marcelo Zabani