Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* ===================================================
* jQuery SelectAll plugin
* ===================================================
* @author: https://gist.github.com/Leegorous
* @license: Licensed under the Apache License, Version 2.0 (the "License"),
* see http://www.apache.org/licenses/LICENSE-2.0
* ===================================================
*
* Example:
*
* HTML >>
* <div class="container">
* <div class="toolbar">
* <input type="checkbox" class="selector-all" /> ALL/None
* </div>
* <div class="row">
* <input type="checkbox" class="selector" /> Sth bala bala...
* </div>
* <!-- repeat .row -->
* </div>
*
*
* JS >>
* $('.container').selectAll({
* selectorAll: '.selector-all'
* , selector: '.selector'
* , controller: $('.container')
* })
*
* All options are optional.
*
* When user click on the the checkboxs, it will fire an event
* named "change:select" on $('.container'), with the following data:
*
* {
* total: 20
* , selected: 1
* }
*
* The "controller" should be an object like this:
* {
* trigger: function(eventName, data) {...}
* }
*/
!(function($) {
$.fn.selectAll = function(options) {
options = options || {}
var ctn = $(this)
, allSel = options.selectorAll || '.selector-all'
, sel = options.selector || '.selector'
function fireEvent(total, selected) {
if (options.controller && typeof options.controller.trigger === "function") {
options.controller.trigger('change:select', {
total: total
, selected: selected
})
}
}
ctn.on('click', allSel, function(evt) {
$(sel, ctn).prop('checked', $(evt.currentTarget).is(':checked'))
fireEvent($(sel, ctn).length, $(sel + ':checked', ctn).length)
})
ctn.on('click', sel, function(evt) {
var selected = $(sel + ':checked', ctn).length
, total = $(sel, ctn).length
$(allSel, ctn).prop('checked', selected === total)
fireEvent(total, selected)
})
return this
}
})(jQuery);
@sconts

This comment has been minimized.

Show comment
Hide comment
@sconts

sconts Mar 29, 2014

thank you very much.

sconts commented Mar 29, 2014

thank you very much.

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