Get <td> values only in specific rows using jQuery

不羁岁月 提交于 2019-12-07 07:43:05

问题


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.


回答1:


<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>   



回答2:


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!




回答3:


$('#docsTable > tr > td > input:checked').each(function(i,element){

var el = $(element);
alert( el.val() );
alert( el.parent().siblings(':eq(0)').html() );
alert( el.parent().siblings(':eq(1)').html() );

});


来源:https://stackoverflow.com/questions/6310594/get-td-values-only-in-specific-rows-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!