使用.each()循环选中复选框和.append数据

时间:2012-08-25 19:21:39

标签: jquery loops each

我在表格中有一系列行,每行都有不同的值(价格),每行都有一个复选框。该表是通过PHP循环生成的。

echo "<table border='0' cellpadding='10' id='booking-list'><tr>";
echo "<th>Booking ID</th><th>Customer ID</th><th>Start Date</th><th>Course Name</th><th>Amount Due</th><th>Date Payment Due</th><th>Add to basket</th></tr>";
$x = 0; 
while ($row = mysql_fetch_assoc($query)) {
    $balance = $row['price'] - $row['deposit'];

    echo "<td>" .$row['booking_id']. "</td><td>" .$cust_id. "</td><td>" .$row['start_date']. "</td><td>" .$row['name']. "</td><td>" .$balance. "</td><td>" .$row['balance_due_date']. "</td><td><input type='checkbox' name='' value='" .$x. "' /></td></tr>";
    $x++;
}
echo "</tr><table>";

对于选中的每个复选框,我想将(.append)特定值($balance)添加到form输入字段。附加部分似乎正在工作,但我不知道如何循环遍历jQuery中的每个复选框以获取我需要的值。

function(){
    $('#booking-list input:checkbox').change(
        function(){
            if ($(this).is(':checked')) {
        $('<input />').attr({
                type: 'text',
            id: 'foo',
            name: 'bar',
        value: '<?php echo $balance; ?>'
        }).appendTo('#paypal-form form').text($(this).val());              
            } else {
                $('#paypal-form input:contains('+$(this).val()+')').remove();
            }
        }); 

现在,我只能生成最后$balance个值。

感谢。

4 个答案:

答案 0 :(得分:9)

要选择所有选中的复选框,您可以执行以下操作:

  $('#booking-list input:checkbox:checked').each(function(){
      $(this).doSomething();//this is the checked checkbox
  });

答案 1 :(得分:2)

您在循环后使用$balance,这就是您只获得最后一个值的原因。

要在事件处理程序中直接使用该值,您必须为循环内的每个复选框创建单独的事件处理程序。相反,您可以将余额值放入复选框的数据中:

<input type='checkbox' name='' value='" .$x. "' data-balance='" .$balance. "' />

然后你可以在事件处理程序中使用它:

value: $(this).data('balance')

旁注:现在你只有添加输入的代码,所以如果有人检查了某些内容然后取消选中它,输入仍然存在。

答案 2 :(得分:1)

我想也许是因为你正在重复使用id作为输入。您是否尝试将输入的ID作为$ cust_id?

每个语法如下:

$('selector').each(function (index, currentObject) {
   // index starts with 0
   $(currentObject).doSomething();
});

答案 3 :(得分:0)

您也可以在复选框onClick事件中调用此代码。

$(':checkbox:checked').each(function() {

});
相关问题