单击时单击单选按钮取消选中

bry*_*yan 5 html javascript php mysql radio-button

我有很多单选按钮从我的数据库中获取值,如果设置为"1",我会选中单选按钮.

如果选中单选按钮,并且用户再次单击它,我仍然希望能够清除此按钮.有没有人有想法?

$radio1 从数据库中获取数据,将为0,1或2

<input value="1" name="radio1" type="radio"<?php if($radio1==1){echo " checked";} ?>>
<input value="2" name="radio2" type="radio"<?php if($radio1==2){echo " checked";} ?>>
Run Code Online (Sandbox Code Playgroud)

Varun Malhotra的答案略有修改: 我改变了2行代码,对我来说效果更好.但总的来说,Varun的答案是完美的!

$('input[type="radio"]').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.prop('checked', true);
         $radio.data('waschecked', true);
    }

    // remove was checked from other radios
    $radio.siblings('input[type="radio"]').data('waschecked', false);
});
Run Code Online (Sandbox Code Playgroud)

sof*_*var 12

我建议添加一个自定义属性来跟踪每个无线电的先前状态,如下所示:

$(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);
    });
});
Run Code Online (Sandbox Code Playgroud)

您还需要将此属性添加到最初检查的无线电标记中

<input type="radio" name="rad" id="Radio0" checked="checked" data-waschecked="true" />
Run Code Online (Sandbox Code Playgroud)

JSFIDDLE DEMO

更新:

 $(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[type="radio"]').data('waschecked', false);
        });
    });
Run Code Online (Sandbox Code Playgroud)

但请确保您没有其他无线电组可以使用,否则您必须提供一些属性来指定这些按钮,就像我之前关注的名称一样.

  • 我最后放了`$('input [type ="radio"]').点击`而不是最终工作得非常好.让我知道这是否会引起问题,但到目前为止还是那么好. (2认同)