【问题标题】:Map checked checkboxes to hidden field after element is clicked单击元素后将选中的复选框映射到隐藏字段
【发布时间】:2014-03-05 16:59:02
【问题描述】:

我有一个类为.selectall 的元素。当我单击该元素时,所有表格行都是checked。我想做的是获取选中复选框的所有data-id 值并将它们存储在 ID 为#selected_items 的隐藏字段中。目前我有当前的咖啡脚本,它允许我单独选择每个复选框并将data-id 映射到隐藏字段值。因此,我需要能够单击 .selectall 元素,填充隐藏字段,然后在我决定单独取消选中任何复选框时反映任何更改。

HTML

<div class="btn-group">
    <button class="btn selectall" type="button">Select All</button>
    <button class="btn unselectall" type="button">Unselect All</button>
</div>

<table class="coupons">
    <input class="inline" data-id="1" type="checkbox">
    <input class="inline" data-id="2" type="checkbox">
    <input class="inline" data-id="3" type="checkbox">
    ...
</table>

<input id="selected_items" name="selected_items" type="hidden" value="">

咖啡脚本

$('.coupons input[type="checkbox"]').change(->
    ids = $('input[type="checkbox"]:checked')
        .map(-> $(this).data("id"))
        .get().join(",")

    $("#selected_items").val(ids)
)

【问题讨论】:

    标签: jquery checkbox coffeescript hidden-field


    【解决方案1】:

    试试

    update = () -> 
        ids = $('input[type="checkbox"]:checked')
            .map(-> $(this).data("id"))
            .get().join(",")
    
        $("#selected_items").val(ids)
    
    $('.coupons input[type="checkbox"]').change(update)
    $('.selectall').click(->
        $('input[type="checkbox"]').prop('checked', true);
        update()
    )
    $('.unselectall').click(->
        $('input[type="checkbox"]').prop('checked', false);
        update()
    )
    

    演示:Fiddle - 小幅标记更改,便于调试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 2012-12-30
      • 2017-10-05
      相关资源
      最近更新 更多