Search code examples
javascriptjqueryhtml

How can I toggle radiobutton


Say this is my HTML:

<input type="radio" name="rad" id="Radio0" checked="checked" />
<input type="radio" name="rad" id="Radio1" />
<input type="radio" name="rad" id="Radio2" />
<input type="radio" name="rad" id="Radio4" />
<input type="radio" name="rad" id="Radio3" />

As you can see the 1st radio button is checked. I need the radio button to function like toggle. For eg. If I again click on radio0, all radio buttons should be unchecked.

How can I achieve that?

Update: I don't want any extra buttons. For eg. I could add a button and set the checked property for all radio buttons to be false. However, I don't want that. I only want my form to consist of these 4 radio buttons.

Update: Since most of the people don't understand what I want, let me try to rephrase- I want the radio button to function in toggle mode. I've given the same name to all radio buttons hence it's a group. Now I want the radiobuttons to toggle itself. Eg. if I click on radio0, it should get unchecked if it's checked and checked if it's unchecked.


Solution

  • The problem you'll find is that as soon a radio button is clicked its state is changed before you can check it. What I suggest is to add a custom attribute to keep track of each radio's previous state like so:

    $(function(){
        $('input[name="rad"]').click(function(){
            var $radio = $(this);
    
            // if this was previously checked
            if ($radio.data('waschecked') == true)
            {
                $radio.prop('checked', false);
                $radio.data('waschecked', false);
            }
            else
                $radio.data('waschecked', true);
    
            // remove was checked from other radios
            $radio.siblings('input[name="rad"]').data('waschecked', false);
        });
    });
    

    You will also need to add this attribute to the initially checked radio markup

    <input type="radio" name="rad" id="Radio0" checked="checked" data-waschecked="true" />
    

    See demo here : http://jsfiddle.net/GoranMottram/VGPhD/2/