How can I toggle radiobutton

后端 未结 7 1144
一向
一向 2020-12-31 03:57

Say this is my HTML:



         


        
7条回答
  •  星月不相逢
    2020-12-31 04:32

    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

    
    

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

提交回复
热议问题