Select and Unselect Radio Buttons jQuery code

Cat: jQuery Examples - Cut and Paste Scripts



This is an elegant way to click a radio button to select and unselect it with another click.

No need to change any variables. Just drop it in to your page, or separate linked .js and wha-la.
Click a radio button = it is selected;
Click a selected radio button = it is now unselected.

This is not normal behavior but in some applications it makes sense and can be a great help, rather than have another radio named “none”.

$(function(){
var allRadios = $(‘input[type=radio]’)
var radioChecked;
var setCurrent =
function(e) {
var obj = e.target;

radioChecked = $(obj).attr(‘checked’);
}

var setCheck = function(e) {
if (e.type == ‘keypress’ && e.charCode != 32) {
return false;
}

var obj = e.target;
if (radioChecked) {
$(obj).attr(‘checked’, false);
} else {
$(obj).attr(‘checked’, true);
}
}

$.each(allRadios, function(i, val){
var label = $(‘label[for=’ + $(this).attr(“id”) + ‘]’);

$(this).bind(‘mousedown keydown’, function(e){
setCurrent(e);
});

label.bind(‘mousedown keydown’, function(e){
e.target = $(‘#’ + $(this).attr(“for”));
setCurrent(e);
});

$(this).bind(‘click’, function(e){
setCheck(e);
});

});
});

Original post and demo here – 12Robots
Kudos to 12Robots!

Comments are closed.

Featured & Popular Articles