Archive

Posts Tagged ‘radio’

Advanced radio button grouping with jQuery

November 18, 2009 8 comments

I was asked to do something rather interesting with some radio button inputs the other day. I haven’t come across this particular problem before and google didn’t return anything helpful, so I decided to share what I came up with.

First, the scenario

We have a standard form with 4 radio button groups. Each group has 4 radio buttons labeled from “1” to “4”. Now, when the user selects “option 1” in “group 1”, all the remaining “option 1” items need to be disabled. To see an example in action, you can view the demo here.

The problem

When I first started, I thought that it’s simply a matter of giving each “option” (regardless of group) a common class name – then just disabling all other options with the same class name. That works, to a point, but what if the user changes his mind and selects another option ? Now I had to find all previously disabled options, re-enable them and start all over again.

The solution

Essentially what I came up with was a basic nested loop to handle setting and unsetting the relevant “disabled” attributes. To achieve this, first we assign all “option 1” a class of “number1”, “option 2” a class of “number2” and so on.

Next, we run a basic for loop, and go through each “number” class (i.e. number1 to number4). For each class, we call a function. Inside this function is another loop – this time iterating over each radio button assigned the current class name. Using this loop, we remove any “disabled” attributes which may have been assigned previously. We also find out which item in that group is currently selected (if any) – this is so we can run a second loop to disable all those options not currently selected. Confused ? Now might be a good time to go through the code

The code

$(function(){
		// fire our code when a radio button has been selected
		$("input[type=radio]").change(function(){
			var name = $(this).attr("name"); // get the current button's group name
			$("input[name="+name+"]").removeAttr("selected"); // first we deselect "all" radio buttons within the same group
			$(this).attr("selected","selected"); // make sure our currently "changed" button is selected
			for(i=1;i<=4;i++){ // go through the 4 radio classes
				processRadio(".radio"+i);
			}
		});
		/**
			Loops through each item with same "class" name and disables/enables where appropriate
		**/
		function processRadio(class){
			var empty;
			var id = "";
			var buttons = $(class); // read all buttons with the specified class name into a jQuery object
			buttons.each(function(){ // loop through each item
				var me = $(this);
				var isSelected = me.attr("selected"); // bool value, based on whether the "selected" attribute is present or not
				me.removeAttr("disabled"); // clear the disabled attribute if present
				me.siblings("label").removeClass("disabled"); // same with the associated label element
				if (isSelected != empty && isSelected != ""){
					id = $(this).attr("id"); // set our tmp id var to our currently selected item
				}
			});
			// make sure we have an id, otherwise we'll get an error
			if (id != empty && id != ""){
				buttons.each(function(){ // loop through each radio button once again
					if ($(this).attr("id") != id){ // set the disabled attributes if id attribute doesn't match our tmp id var
						$(this).attr("disabled", "disabled").siblings("label").addClass("disabled");
					}
				});
			}
		}

	});

I’ve commented as best I could, which hopefully makes more sense than my rambling above. Once again, there is a working demo available for you to play with. Be sure to have a look at the markup as well, might clear up a few questions.

I strongly suspect that there’s a more efficient method for achieving the same result – so if you have a better suggestion, tweak or link please let me know – I’d greatly appreciate it.

Advertisements

How to use jQuery to select a radio button from parent element

January 9, 2009 4 comments

A friend asked me for some help on doing the following :
1. You have an unordered list – within each list item you have a radio input.
2. When you click on the list item (i.e. the entire container), it must a) select the radio input and b) add a css classname of “selected” to the list item.

You can find a demo here.

First, the html :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<!-- include our jquery scripts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
    <script src="js/radio.js" type="text/javascript"></script>
    <style type="text/css">
    	li { color: #000; }
    	li.selected { color: #FF0000; }
    </style>
</head>
<body>
	<div>
		<ul>
			<li class="test">Test 1 <input type="radio" name="test" /></li>
			<li class="test">Test 2 <input type="radio" name="test" /></li>
			<li class="test">Test 3 <input type="radio" name="test" /></li>
			<li class="test">Test 4 <input type="radio" name="test" /></li>
			<li class="test">Test 5 <input type="radio" name="test" /></li>
		</ul>
	</div>
</body>
</html>

There is nothing out of the ordinary here – just a simple unordered list of radio inputs.

Next, the js (radio.js) :

$(document).ready(function(){
	$('li').click( function(){
		$('li.selected').removeClass('selected');
		$(this).addClass('selected');
		$(this).children("input[type=radio]").click();
	});
});

1. First – we tell jQuery to execute the following code once the document has finished loading, ensuring that the DOM has been registered successfully.
2. Next we bind a click event to all list item elements on the page – you can of course change this to all list items with a class of “myselection” for example ( $(“li.myselection”).click… )
3. When a list item is clicked – we first need to remove the “selected” class from all other list items.
4. Now we need to add the “selected” class to the list item which fired the event ( $(this) ).
5. Finally, we need to make sure that the radio button inside the list item is “clicked” : we do this by using the .children() selector and executing a click() event on the input.

The important bit is the $(this).children(“input[type=radio]”) selector. What we’re doing here is telling jQuery to find all inputs of type radio (i.e. all radio inputs) inside “this” list item (i.e. the list item which was clicked on). We then use .click() to..as you guessed it… execute a click event on the returned element (in this case the radio input).

And that’s all there is to it. You can read up some more on jQuery selectors here.
I would also highly recommend reading the following article : Improve your jQuery – 25 excellent tips.