使用复选框获取行值

getting the row values with checkbox

本文关键字:获取 复选框      更新时间:2023-09-26

大家好?你能帮帮我吗?我有这个表在HTML。我想要实现的是,当我单击行时,复选框将被选中,行将被突出显示。是否有可能隐藏复选框列?

<table border="1" id="estTable">
<thead>
    <tr>
        <th></th>
        <th>Name</th>
        <th>Age</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td><input type="checkbox"></td>
        <td>Chris</td>
        <td>10</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>Cass</td>
        <td>15</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>Aldrin</td>
        <td>16</td>
    </tr>
</tbody>
</table>
<input type="button" value="Edit" id="editbtn"/>
<div id="out"></div>

,我有这个javascript来获得所选行的值。我希望每次打印一行。

 $('#editbtn').click(function(){
    $('#estTable tr').filter(':has(:checkbox:checked)').find('td').each(function() {
         $('#out').append("<p>"+$(this).text()+"</p>");
        });
});

当您使用类向源代码中添加更多上下文时,这会变得容易一些:

<tr>
    <td class="select hidden">
        <input type="checkbox">
    </td>
    <td class="name">Chris</td>
    <td class="age">10</td>
</tr>

然后你可以这样做:

$(document).ready(function () {
    'use strict';
    $('#estTable tbody tr').click(function (e) {
        //when the row is clicked...
        var self = $(this), //cache this
            checkbox = self.find('.select > input[type=checkbox]'), //get the checkbox
            isChecked = checkbox.prop('checked'); //and the current state
        if (!isChecked) {
            //about to be checked so clear all other selections
            $('#estTable .select > input[type=checkbox]').prop('checked', false).parents('tr').removeClass('selected');
        }
        checkbox.prop('checked', !isChecked).parents('tr').addClass('selected'); //toggle current state
    });
    $('#editbtn').click(function (e) {
        var selectedRow = $('#estTable .select :checked'),
            tr = selectedRow.parents('tr'), //get the parent row
            name = tr.find('.name').text(), //get the name
            age = parseInt(tr.find('.age').text(), 10), //get the age and convert to int
            p = $('<p />'); //create a p element
        $('#out').append(p.clone().text(name + ': ' + age));
    });
});

实时演示:http://jsfiddle.net/Lf9rf/

如果我理解"一次打印一行"正确,我认为你需要清空你的"out"选择器之前执行新的调用

$('#editbtn').click(function(){
    $('#out').empty();
    $('#estTable tr').filter(':has(:checkbox:checked)').find('td').each(function() {
        $('#out').append("<p>"+$(this).text()+"</p>");
    });
});

jsBin demo

CSS:

.highlight{
    background:gold;
}
jQuery:

$('#estTable tr:gt(0)').click(function( e ){ 
  var isChecked = $(this).find(':checkbox').is(':checked');
  if(e.target.tagName !== 'INPUT'){
      $(this).find(':checkbox').prop('checked', !isChecked);
  }
  $(this).toggleClass('highlight');
});