How to check/uncheck radio button on click?

后端 未结 18 1444
情深已故
情深已故 2020-11-29 02:16

I want to be able to uncheck a radio button by clicking on it.

So, if a radio button is unchecked, I want to check it, if it is checked, I want to uncheck it.

<
18条回答
  •  孤独总比滥情好
    2020-11-29 02:27

    The accepted answer does not work on mobile devices. It relies on setTimeout and bindings that are related to mouse events that just don't fire on tablets/mobile devices.
    My solution is to manually track the selected state using the "click" event handler and a custom class state.

    1. handle the click events on the radio input elements
    2. check if the "selected" class exists on the clicked element
    3. if it does, (meaning it has been clicked before), remove the class and uncheck the element, return
    4. if it doesn't, remove the class from all elements of the same name and add it to only the clicked element.

    No need to prevent default behaviors. Here is the code in Jquery:

    $("input:radio").on("click",function (e) {
        var inp=$(this); //cache the selector
        if (inp.is(".theone")) { //see if it has the selected class
            inp.prop("checked",false).removeClass("theone");
            return;
        }
        $("input:radio[name='"+inp.prop("name")+"'].theone").removeClass("theone");
        inp.addClass("theone");
    });
    

    http://jsfiddle.net/bhzako65/

提交回复
热议问题