cup_of
cup_of

Reputation: 6687

How to toggle a radio button on and off using jQuery?

Hello I have a radio button I need to be able to toggle on and off. I know I should use a checkbox but unfortunately I am constrained to use radio buttons for reasons that would be too long to explain.

Its a single radio button so when I click on it, theres no way to turn it off.

Is it possible to toggle a single radio button on and off using jQuery?

This is what I have so far, but I cant get it to work.

    jQuery('.gfield_radio li input').click(function() {
        if(jQuery(this).is(':checked')) {
            jQuery(this).prop('checked', true);
        }

        else if (!jQuery(this).is(':checked')) {
            jQuery(this).prop('checked', false);
        }
    });

Any help would be greatly appreciated!

Thanks

Upvotes: 2

Views: 7680

Answers (1)

Marco Magrini
Marco Magrini

Reputation: 749

I wouldn't personally use a radio button. Anyway the code below is gonna work.

    var radioState;

    $('.my-radio').on('click', function() {
        if (radioState === this) {
            this.checked = false;
            radioState = null;
        } else {
            radioState = this;
        }
    });

jsfiddle here: https://jsfiddle.net/n76uvo00/

Upvotes: 9

Related Questions