Skip to content

Instantly share code, notes, and snippets.

@fokayx
Created April 28, 2015 08:32
Show Gist options
  • Save fokayx/2b142b49d6ac4618a62b to your computer and use it in GitHub Desktop.
Save fokayx/2b142b49d6ac4618a62b to your computer and use it in GitHub Desktop.
Easiest "check all" ever with jQuery._Brian Cray

##超簡單jQuery:"check boxes checked all/ 全選"功能

原文出處:Brian Cray

要怎麼做出全選效果呢? 將checkbox放入同一區的fieldset中,再加上script,就可以進行全選或全不選的操作。請看下面範例:

###HTML:

<fieldset>
    <!-- 在同一個fieldset中的checkbox會被勾選-->
    <div><input type="checkbox" class="checkall"> Check all</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>
<fieldset>
    <!-- 因為屬於不同的fieldset,所以這一區的checkbox不會受影響-->
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>

###Script:

$(function () {
    $('.checkall').on('click', function () {
        $(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
    });
});

沒錯就這樣,即可以輕鬆分區做全選或全不選。Brian 說他花了許多時間精簡這段程式碼,最後才能如此簡單明暸又有效率,好好享用!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment