Question

I have an element with the class of .selectall. When I click that element, all table rows are then checked. What I would like to do is take all the data-id values of the checked checkboxes and store them in a hidden field with the ID of #selected_items. At the moment I have the current coffeescript that allows me to select each checkbox individually and map the data-id to the hidden field value. So I need the ability to click the .selectall element, have the hidden field populate, and then reflect any changes if I decide to individually uncheck any of the checkboxes.

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

Coffeescript

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

    $("#selected_items").val(ids)
)
Was it helpful?

Solution

Try

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

Demo: Fiddle - minor markup changes for easy debugging

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top