Last active
February 9, 2017 09:08
-
-
Save Leegorous/5941921 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* =================================================== | |
* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you very much.