Skip to content

Instantly share code, notes, and snippets.

@Leegorous
Last active February 9, 2017 09:08
Show Gist options
  • Select an option

  • Save Leegorous/5941921 to your computer and use it in GitHub Desktop.

Select an option

Save Leegorous/5941921 to your computer and use it in GitHub Desktop.
/* ===================================================
* 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);
@hzbd
Copy link
Copy Markdown

hzbd 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