Category Archives: HTML & CSS

Making a Radio Group Tab-able Using jQuery

Recently I had to come up with a solution to make radio boxes tab-able. Mozilla Firefox allows you to tab over each radio box in a group, however, all other browsers do not. The solution is actually quite simple. First, in your HTML make sure to name your radio boxes with the same name, but also add a .1, .2, .3, and so on, to separate them. You will also need a hidden element. This is the one you want to do validation against. For example:

    
     Radio 1
     Radio 2
     Radio 3

Now add a little bit of code that will parse once the DOM is ready:

    
        $(document).ready( function() {
            rt = new RadioTabs();
            rt.init( "group1", ["group1.1", "group1.2", "group1.3"], ["click"] );
        });
     

All this does is tell the RadioTabs class (coming next) which tabs will be in the group. Finally, add this somewhere on you page. Preferably on a separate page.

	/* Create Tabable Radio Boxes */
	function RadioTabs() {
		/* Declare Private Members and Methods */
		var hidden = '';
		var group = [];
		var events = [];

		/* void Bind Events to each individual Radio Box */
		var bindEvents = function () {
			//Loop through Events
			for( var e = 0; e < events.length; e++ ) {
				//Loop through Radio Buttons
				for( var g = 0; g < group.length; g++ ) {
					//Add a Rel value to each group box - to be used in the bind
					$('input:radio[name="' + group[g] + '"]').attr('rel', g);
					//Bind actual events to each radio box
					$('input:radio[name="' + group[g] + '"]').bind(events[e], function( event ) {
						var n = $(this).attr('rel');
						$('[name="' + hidden + '"]').val( $('[name=' + group[n] + ']').val() );
						//Step through radio group and set to false
						for( var i = 0; i < group.length; i++ ) {
							if( group[i] != group[n] ) {
								$('input:radio[name="' + group[i] + '"]:checked').attr( 'checked', false );
							}
						};
					});
				}
			}
		};
	 
		/* Declare Public Members and Methods */
		return {
			/* string Set the Hidden Input Element */
			setHidden    : function ( value ) {
				hidden = value;
			},
			/* array Set the Radio Group Elements */
			setGroup    : function ( values ) {
				group = values;
			},
			/* array Set the Events to bind to */
			setEvents    : function ( values ) {
				events = values;
			},
			/* void Init the script */
			init            : function ( hid, grp, evt ) {
				this.setHidden( hid );
				this.setGroup( grp );
				this.setEvents( evt );
				bindEvents();
			}
		};
	};

All the above piece of code does is it will allow you to tab through the radio boxes, and then set the hidden elements value to that of the selected radio box. You might have to tweak a little bit with CSS in IE7 and 8 (I don’t support 6 anymore) to make it show that the box is selected. This should do the trick

    input[type=radio]:focus {
        outline:#000 dotted thin;
    }
Share: