jQuery Tip: Radio Button Deselection

As a web developers we sometimes get things thrown at us that for whatever reason it makes sense for the behavior of something to be changed.  Normally I push back in these situations waving the big User Experience stick at people, but sometimes the request actually  makes sense.

Recently while working on a survey page for a client that was entirely radio button driven I was asked for the ability to allow a user to de-select a radio button.  The answers Google returned for me mostly said “radio buttons should always have one value, they aren’t designed for de-selection.”

The problem with this particular set of buttons was it was the weighting in the survey the user assigned to the ‘Other’ field.  If the user selected a radio button they were then forced to have to enter their own text with no way of deciding the no longer wanted to enter an optional “other” item.  This was also the only optional field in the entire survey.  The other problem was purely aesthetic with a “no selection” selection not working with the design.  It was decided a second click on the radio button would de-select the selection.

I thought it would be easy – I’ll just cancel the onClick event on that object.  Unfortunately Firefox didn’t like that idea.  It seems that when the onClick event is fired, the radio button is already selected, so retrieving the previous selection’s value didn’t work.  The way I dealt with this was a two-pronged approach using both the mouseDown and click events.

Implementation

Firstly I added a new radio button with “display: none” and gave it a value of 0 so that I had something to select, this should go before the other radio buttons in the group as it’s referenced as index 0 using .eq(0).

       <input type="radio" name="q1e" style="display: none;" value="0" />

And the jQuery magic to make the de-selection happen:


       $('[name=q1e]').mousedown( function() {
		$(this).data('previous', $('[name=q1e]:checked').val() );
	});

	$('[name=q1e]').click( function(e) {
		if( $(this).val() == $(this).data('previous') ) {
			$('[name=q1e]').eq(0).attr('checked', true);
			$(this).blur();
			e.preventDefault()
		}
	});
You can leave a response, or trackback from your own site.

One Response to “jQuery Tip: Radio Button Deselection”

  1. Ben Greeley says:

    Clever solution! I was having the very same issue and your post definitely helped figure out what the heck was going on. Thanks!

Leave a Reply