Checkbutton and Radiobuttons revisited: a jQuery plug-in.

Thursday, 25 March 2010 00:45 by Tom Gröger

 

Well some time ago I posted the code for a jquery plugin to Radiobutton-Groups  ( a jQuery Room for Radiogroups) . As usual, soon after I had finished my code I came across a problem where I had to manage a large group of check buttons. Not a big deal though, after all check buttons are much like radio buttons, except that the later normally should return a value indicating which of the buttons in the group has been selected ( and while there is only one radio button possibly selected at a time, this makes perfect sense ). 

Check buttons in comparison are mostly used to return a bit value – checked or not checked. Before Ajax a check button value was necessary because the only way a checkbox could tell the Server whether it was checked or was to set its value into the Request.Form collection, but fortunately times are a-changing: Now all we need to know is it’s checked state. Also, check buttons can be grouped together to a logical unit, but it doesn’t make sense for such a group to return a single value as with radio groups - this differences had to be handled in order to create a plug in that would manage both radio- and check button groups.

 

The outcome was a JQuery plugin, or better two plug ins:

 

 btngroup

$.fn.Checkbox wraps a check- or radio button Input and its associated text label. The jQuery wrapper is extended with a disable- and enable method that will not only enable/disable the button but also the label – as you can see in the screenshot from one of my apps. 
If the wrapped control is a check button then the native jQuery val()  method is overwritten to set/get true/false values both reflecting and setting the checked state.

 

Let’s play a typical scenario for a checkbox like this:

<label for="chk">Thirsty ?</label><input type="checkbox" id="chk" />

 

Assume that you want to uncheck the button, disable it, and change the text of the Label:

with the Checkbox plugin this is a one-liner:

// Create a Checkbox object

var jCheck= $("#chk").Checkbox();

jCheck.uncheck().disable().label.text("Drunk!");

 

// Read the state of our Checkbox

var IsFilled = jCheck.checked();

 

// You can also use the val() method to set/get the checked state

var IsFilled = jCheck.val();

 

// Set the checked state of our Checkbox

jCheck.checked( bIsSober );

 

Same applies to a Radio Button,  although a single Radio Buttons doesn’t make a lot of sense.
If you want to work with Grouped check- or radio buttons then we use the second plugin:


$.fn.ButtonGroup extends a jQuery container object ( usually a table or fieldset ) that wraps a couple of radio- or checkbox buttons together with their associated labels.  The ButtonGroup then allows you to easily set/get a Radio group's value,  disable- or enable the complete Group (including labels) or only selected buttons. Internally the ButtonGroup is no more than a list of $.fn.Checkbox objects that wrap the check or radio buttons and some code to bring it all together. The modified get() method returns such an extended button object that also  'understands' checked/enable/disable messages.

By default the control expects and returns integer values. If no button is selected at all then

ButtonGroup.val() will return a Zero ( or –1, if Zero is a valid value for one of the Buttons) . These values can be overwritten by an options object passed as a constructor parameter as usual for many jQuery plugins.

 

Lets create a little button group:

<table id="tbGroup">
    <tr>
        <td><input type="radio" id="rad0" name="radCity" value="1" /></td>
        <td><label for="rad0">German citizen by birth</label></td>
    </tr>                
    <tr>
        <td><input type="radio" id="rad1" name="radCity" value="2" /></td>
        <td><label for="rad1">Acquired German citizenship:</label></td>
    </tr>                
    <tr>
        <td><input type="radio" id="rad2" name="radCity" value="3" /></td>
        <td><label for="rad2">Not a German citizen</label></td>
    </tr>                
</table>

Nothing unusual so far, three Radio buttons ( could be Check buttons as well ) grouped together with a common name property “radCity”.  In this case we use a Table to give our buttons a container ( and proper layout ), but you can also use a div-tag or whatever tags you prefer – this container will  the prime candidate for our ButtonGroup:

 

Using the ButtonGroup Control:

// Create the Radio ButtonGroup var jGroup = $("#tbGroup").ButtonGroup();

 

jGroup.disable(0); // Disable the first Button

jGroup.disable(0,2); // Disable Buttons 0 and 2

jGroup.val("1"); // Set a value and so select button 0

 

var IDRadio = jGroup.val().toInt(); // read the radio group value .

 

jGroup.get(0); // returns first button object

jGroup.get(1,2); // returns Array with button 1 and 2

jGroup.get("checked"); // returns selected Radio Button

 

 

// Disable all buttons, remove selection, enable one button and select it

if ($Controls.chkNoRelatives.checked()) {
    $Controls.tbGroup.disable().uncheck().get("rad1").enable().checked(true);
};

 

This short example might give you an impression about the power and simplicity of this plugin, imagine you’d have to code the last example by hand ! Please visit the ButtonGroup Live Demo Page  for a short demonstration of Radio- and Checkbox Groups.  Comments and Improvements appreciated !



Resources:


 

A jQuery-Room for RadioGroups

Wednesday, 30 December 2009 16:14 by Tom Gröger

Please note: This Code has been revised and replaced by the ButtonGroup plugin!

So one day I had enough of reading about the oh-so great jQuery Library and decided to give it a try. After all what could be so exciting about a JavaScript library ? Just a couple of methods to select a Dom element? Man, was I wrong - learning jQuery completely changed my way of programming.

More than a year later now I have moved most of my UI code into my JavaScript Framework, using jQuery as my Control-container and Ajax engine ( and for all the other neat stuff that it does ). One thing I always stumbled upon was the use of Radio buttons; like Check buttons they can be checked or not, but unlike them they can be combined to a Radio group that returns a value. My first shot was to wrap the Radio group into a jQuery object and then work on it:

<div id="container">
<input type="radio" id="rad1" name="radKult" value="1" />
<label for="rad1">free drinks</label>
<input type="radio" id="rad2" name="radKult" value="2" />
<label for="rad1">paid drinks</label>
</div>
// Create RadioGroup wrapper and set/get value
jGroup = $("#container input:radio");
var sel = jGroup.filter(':checked').val()
jGroup.attr("checked", "checked");


Ok, that worked somehow, but honestly it was a pain in the rear and most of the time I found myself working with the Dom elements again. The other problem I had with this approach was that while I could easily enable or disable the Radio buttons, but not the attached Labels.

So, finally I came across this problem once too many and sat down to write a jQuery plug-in:


The RadioGroup Control:


The Control should be an extended jQuery object with some methods added and others overwritten. The jQuery part would only wrap the radio buttons,  and the inner class keeps its own a list of radio button objects and associated labels.

  • The val() method is overwritten to easily return and set the Radio group's value
  • The enable() and disable() methods should enable and disable either the complete group (including labels) or only selected buttons
  • The modified get() method will return an extended Radio button object that also understands checked/enable/disable messages


The Code itself is simple and straightforward, inside my controls I do prefer to use the DOM methods ( for performance reasons ) whenever possible:


   ////////////////////// RadioGroup //////////////////////////
    

$.fn.RadioGroup = function() {
/// <summary>
/// JQuery plugin that creates a TomSoft.Form.RadioGroup object and
/// attaches this to the Wrapper of the RadioGroup-Container.
/// <returns type="jQuery" />

if (this.length != 1) {
throw new Error("bad selector for RadioGroup " + this.selector,
"window.document");
return this;
}

var items = [];
_init(this);

//
// JQuery object extensions
//
this.val = function(value) {
/// <summary>
/// Returns the value of the checked radio button within the Group
/// or checks the radiobutton with the given value. if the value
/// does not exist then the radiogroup remains unchecked
/// </summary>

if (arguments.length) {
value = value.toString(); // setter
for (var i = 0; i < items.length; ++i) {
var j = items[i];
j.checked(false);
if (value == j.val()) {
j.checked(true);
break;
};
};
return this;
}
// getter
var j = this.selected();
return ((j) ? j.val() : -1);
};

this.enable = function(bEnable) {
/// <summary>
/// enable/disable RadioGroup and associated Labels
/// </summary>
bEnable = (typeof (bEnable) == 'boolean') ? bEnable : true;
for (var i = 0; i < items.length; ++i) {
items[i].enable(bEnable);
}
return this;
};

this.disable = function() {
/// <summary>
/// if called without arguments the method disables all RadioButton
/// and associated Labels. If numeric arguments are passed then
/// all RadioButtons of the group are enabled except those with
/// matching the index position.
/// </summary>
/// <example>
/// $Controls.radioGroupHerkunft.disable(1,4,5);
/// </example>
if (arguments.length) {
for (var i = 0; i < items.length; ++i) {
// check if pos i is in the argument list to be disabled
var bEnable = ($.inArray(i, arguments) == -1);
items[i].enable(bEnable);
};
return this;
};
return this.enable(false);
};

this.selected = function() {
/// <summary>
/// Returns the checked radiobutton within the Group
/// </summary>
for (var i = 0; i < items.length; ++i) {
if (items[i].checked()) {
return items[i];
};
};
return null;
};

this.get = function(index) {
/// <summary>
/// Returns modified RadioButton Object by position or ID(s):
///
/// radio.get( 0 ) returns first jRadioLabel
/// radio.get( 0,2,3 ) returns Array of buttons in Pos 0,2 and 3
/// usage: $.each( radio.get(0,..),
/// function(){this.disable()})
/// radio.get("checked") return selected jRadioLabel
/// radio.get("all") return list array of all Radio Buttons
/// </summary>

var list = [];

for (var cx = 0; cx < arguments.length; ++cx) {
var arg = arguments[cx];
if (typeof (arg) == 'string') {
if (arg == "checked") return this.selected();
if (arg == "all") return items;

for (var i = 0; i < items.length; ++i) {
if (items[i].radio.id == arg)
list.push(items[i]);
};
}
else if (arg >= 0 && arg < items.length) {
list.push(items[arg]);
};
};
if (list.length)
return (list.length == 1) ? list[0] : list;

return;
};

return this;


//
// Initialize the object
//
function _init(jObj) {

var jLabel = $("label", jObj);
var jRadio = $(":radio", jObj);
for (var i = 0; i < jRadio.size(); ++i) {
items.push(_jRadioLabel(jRadio.get(i), jLabel.get(i)));
};
};

//
// Creates a modified jQuery Object-Wrapper for the given Radio/Label pair
// The jQuery radio Object has some added methods and properties:
// .radio: returns the dom-RadioButton Object
// .label returns the jQuery-Label Object
// .checked: gets/sets the checked state of the RadioButton
//
function _jRadioLabel(radio, label) {

var jRadio = $(radio);

jRadio.radio = radio;
jRadio.label = $(label);

if (jRadio.label.size() == 1)
label.htmlFor = radio.id;

jRadio.checked = function(bChecked) {
/// <summary>
/// gets or sets the checkded state of the RadioButton
/// </summary>
/// <returns type="boolean">checked state</returns>
if (arguments.length) {
bChecked = (typeof (bChecked) == 'boolean') ? bChecked : true;
radio.checked = bChecked; // setter
return jRadio;
};
return radio.checked; // getter
};

jRadio.enable = function(bEnable) {
/// <summary>
/// enable/disable RadioButton and associated Label
/// </summary>
bEnable = (typeof (bEnable) == 'boolean') ? bEnable : true;
radio.disabled = !bEnable;
jRadio.label.css("color", bEnable ? "" : "#ccc")
if (!bEnable) radio.checked = false;
return jRadio;
};

jRadio.disable = function() {
/// <summary>
/// diables RadioButton and associated Label
/// </summary>
return jRadio.enable(false);
};

return jRadio;
};
};


Using the RadioGroup Control:



The usage should be intuitive and easy, yet give you access to every single element of the Radio Group:
jGroup=$("#container").RadioGroup();  // Create extended RadioGroup Object
jGroup.disable(0);                    // disable the first button
jGroup.disable(0,3,4);                // disable a list of radio buttons
jGroup.val("1"); // Set a value and so select a button db.IDRadio = jGroup.val().toInt(); // read the radio group into a field ..
jGroup.get(0); // returns first button as jQuery object jGroup.get(1,2); // returns Array of two jQuery radio buttons jGroup.get("checked"); // return selected jQuery radio button
var domRadio = jGroup.get(0).radio; // access the radio Dom object var domLabel = jGroup.get(0).label; // access the label Dom object

 

Resources:




  ,
  ASP.NET | JavaScript | jQuery
  E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed