Last Updated: February 25, 2016
· bjacog

Jquery Radio buttonset allow deselect

If you have a couple of radio's in a button set (or not) and want to be able to "unselect" any selected item you can implement the below fix which uses a custom param in the HTML and jquery.

<!-- HTML -->
    <div id="radio">
        <input type="radio" id="radio1" name="radio" checkstate="false" /><label for="radio1">Choice 1</label>
        <input type="radio" id="radio2" name="radio" checkstate="true" checked="checked" /><label for="radio2">Choice 2</label>
        <input type="radio" id="radio3" name="radio" checkstate="false" /><label for="radio3">Choice 3</label>

Here is the jquery attached to onclick of the radio's, on ready.

<!-- JS -->
<script type="text/javascript">


        //if this item is already ticked, make it unticked.
        if ($(this).attr('checkstate') == 'true')
            $(this).attr('checked', false);
            $(this).attr('checkstate', 'false');  // .attr returns a string for unknown param values.
            $(this).attr('checked', true);
            $(this).attr('checkstate', 'true');
        //refresh the buttonset to display the states correctly.

}); //close onready


4 Responses
Add your response

Nice script.

Here are a couple of things that I would change:

  1. Store $(this) inside a variable (perhaps $this) as this will help make your code more readable when it starts to get lengthy.

  2. Chain whenever possible. For example: $(this).attr('checked', false).attr('checkstate', 'false');

over 1 year ago ·

+1 for chaining, I generally don't like putting $(this) in a variable but I guess it would make it a bit clearer what you are operating on. Thanks for the comment. Do you know if chaining has any performance advantage?

over 1 year ago ·

Great script! Thanks! :D

I don't think chaining has a performance (dis)advantage, but calling multiple times $(this) has. So call as few $(this) as possible: I suggest making a variable, so you have to call $(this) only once, even if you don't like it :p :
var context = $(this)

over 1 year ago ·

Your html doesn't match your javascript. You're calling buttonset on a class called radio, when that's the ID. There is no .button_bar. Someone trying to use this will have to figure out exactly what they have to do to get the UI to refresh properly. For me, I had to remove the ui-state-focus class on the label element. Also, the change event won't fire if the user untoggles the radio using this method.

over 1 year ago ·