radiocheckbox JQuery plugin
For short: Uncheckable radio button.
Background
Representing boolean values in HTML form is simple. Everyone is using checkboxes for that. Until a client has a need of representing the a “third” value (e.g.: making decision of yes or no or no decision). In that situation the radiobutton is the proper solution. But radiobutton has one major disadvantages: it cannot be unchecked.
Usage
1<script type="text/javascript"> 2$().ready(function() { 3 $('.test').radiocheckbox({ 4 defaultValue : 2, 5 domainValues : [ { 6 label : 'No', 7 value : 0 8 }, { 9 label : 'Yes', 10 value : 1 11 } ] 12 }); 13}); 14</script> 15<span class="test" data-value="0" data-name="fieldName1"></span> 16<hr /> 17<span class="test" data-value="1" data-name="fieldName2"></span> 18<hr /> 19<span class="test" data-value="2" data-name="fieldName3"></span>
Source
1;(function($, window, document, undefined) { 2 // Create the defaults once 3 var pluginName = "radiocheckbox", defaults = { 4 propertyName : "value" 5 }; 6 7 // The actual plugin constructor 8 function Plugin(element, options) { 9 this.element = element; 10 this.options = $.extend({}, defaults, options); 11 12 this._defaults = defaults; 13 this._name = pluginName; 14 this._id_counter = 0; 15 16 this.init(); 17 } 18 19 Plugin.prototype = { 20 init : function() { 21 var initial_value = $(this.element).data('value'); 22 var base = this; 23 var field_name = $(this.element).data('name'); 24 var id_default = this.generate_id(field_name); 25 var items = []; 26 _.each(base.options['domainValues'] ,function(d, index, list){ 27 var id_c = base.generate_id(field_name); 28 items.push('<label><input id="' + id_c + '" type="checkbox" name="' + field_name + '" value="'+d.value+'" ' 29 + base.checked(initial_value, d.value) + '></input>'+d.label+'</label>'); 30 }); 31 items.push('<input id="' + id_default + '" type="hidden" name="' + field_name + '" value="2"></input>'); 32 $(items.join('')).appendTo($(base.element)); 33 34 //`.change` or `.click` 35 $('input', $(base.element)).change(function(e) { 36 var current_checkbox = this; 37 if(!$(current_checkbox).prop('checked')){ 38 return true; 39 } 40 var others_checked = !$(current_checkbox).prop('checked'); 41 $(':checkbox', $(base.element)).each(function() { 42 if (this !== current_checkbox) { 43 $(this).prop('checked', others_checked); 44 } 45 }); 46 }); 47 }, 48 49 checked : function(currentVal, domainVal) { 50 if (currentVal === domainVal) { 51 return 'checked'; 52 } 53 return ''; 54 }, 55 generate_id : function(prefix) { 56 return prefix + (this._id_counter++); 57 } 58 }; 59 60 $.fn[pluginName] = function(options) { 61 return this.each(function() { 62 if (!$.data(this, "plugin_" + pluginName)) { 63 $.data(this, "plugin_" + pluginName, new Plugin(this, options)); 64 } 65 }); 66 }; 67 68})(jQuery, window, document);
Demo
Aug 24, 2013
comments powered by Disqus