I was looking for a script that allows me to deselect a radio button. I found one on SO and implemented it here…
http://jsfiddle.net/sparky672/YFsVK/1/
As you can see it’s working great but only when you click on the radio button itself. (You can also “select” a button by clicking on its corresponding <label> text. This is how the <label> operates by default.)
However, I also need to be able to “deselect” a radio button by only clicking on its corresponding <label>, and this is where I need some help.
(Why? Because I’m using a plugin that graphically alters the look of the radio button using an image sprite contained within the <label> that covers over the default radio buttons. There is a line within my jsFiddle you can activate to see the plugin in action.)
I’m sure I just need to tweak this script a bit but I cannot seem to get it correct. I believe I just need to “select” the <label> while manipulating the corresponding radio button. A <label> is “attached” to a button by placing the id of the button in the for attribute of the corresponding <label>.
JavaScript:
$(document).ready(function() {
$('input[name="amount"]').mousedown(function(e) { // allows radio button deselection
var $self = $(this);
if ($self.is(':checked')) {
var uncheck = function() {
setTimeout(function() {
$self.removeAttr('checked');
}, 0);
};
var unbind = function() {
$self.unbind('mouseup', up);
};
var up = function() {
uncheck();
unbind();
};
$self.bind('mouseup', up);
$self.one('mouseout', unbind);
}
});
});
HTML:
<fieldset id="radioset">
<input type="radio" id="radio-1" name="amount" value="Option 1" /><label for="radio-1" title="">Option 1</label><br />
<input type="radio" id="radio-2" name="amount" value="Option 2" /><label for="radio-2" title="">Option 2</label><br />
<input type="radio" id="radio-3" name="amount" value="Option 3" /><label for="radio-3" title="">Option 3</label><br />
<input type="radio" id="radio-4" name="amount" value="Option 4" /><label for="radio-4" title="">Option 4</label><br />
<input type="radio" id="radio-5" name="amount" value="Option 5" /><label for="radio-5" title="">Option 5</label>
</fieldset>
I also tried what @Jrod did and noticed the plugin didn’t work. So I modified the plugin. Basically adding this to the label:
Here is an updated demo.