2

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

cup_of
  • 6,397
  • 9
  • 47
  • 94
  • Not a direct answer, but does it have to *be* a radio button, or just *look like* a radio button? You can use CSS to style a checkbox so it looks like a radio button (`appearance: radio`), if that helps. Not sure what the browser support is for it these days. – Jim Stewart Nov 19 '16 at 00:17
  • thanks for your answer, unfortunately i need to use a radio button – cup_of Nov 19 '16 at 00:18
  • I personally would love to hear these "reasons that would be too long to explain" – CrayonViolent Nov 19 '16 at 00:26
  • i am using a wordpress plugin called gravity forms, and my work has a specialized plugin that works with gravity forms that was specifically created for us and for what we do. some reason checkboxes dont work with our plugin but radio boxes work @CrayonViolent – cup_of Nov 19 '16 at 04:02

1 Answers1

9

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/

Marco Magrini
  • 749
  • 1
  • 9
  • 19