繁体   English   中英

单选按钮第二次单击取消选中

[英]Radio button second click makes uncheck

如果我的单选按钮先前已选中,并且我尝试通过第二次单击取消选中,我必须再次单击。 所以这意味着如果我的单选按钮之前选中了,我必须单击 2 次才能取消选中,但它应该只需要单击 1 次。 我该如何解决。 这是两个代码,它们都有相同的问题。 我在这里显示两个脚本。感谢您的帮助!

 $(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);
    });
});

 $("input:radio").on("click", function (e) {
    var inp = $(this);
    if (inp.is(".clicked")) {
        inp.prop("checked", false).removeClass("clicked");
    } else {
        $("input:radio[name='" + inp.prop("name") + "'].clicked").removeClass("clicked");
        inp.addClass("clicked");
    }
});

<input type="radio" name="rad" id="Radio0" checked="checked"/>
<input type="radio" name="rad" id="Radio1" />
<input type="radio" name="rad" id="Radio2" />
<input type="radio" name="rad" id="Radio4" />
<input type="radio" name="rad" id="Radio3" />

这是我的 html 和 jsfiddle

http://jsfiddle.net/fbyg1htz/

http://jsfiddle.net/7g684219/

默认选择的输入元素( checked="checked" )应该将waschecked数据属性设置为 true,因为它已经被选中。

<input type="radio" name="rad" id="Radio0" data-waschecked="true" checked="checked"/>

第二个例子也是如此。 您应该将class="clicked"添加到最初检查的元素中。

<input type="radio" name="rad" id="Radio0" class="clicked" checked="checked"/>

更新的小提琴:

http://jsfiddle.net/6fqLexbr/

http://jsfiddle.net/rmuh1sz3/

第一个脚本的 razor 示例:

<input type="radio" id="status_active" value="true" asp-for="ActiveOrPassive"
       data-waschecked="@Model.OrderFilter.ActiveOrPassive.ToString().ToLower()" />

对于你的第二个脚本:

<input type="radio" id="status_active" value="true" asp-for="ActiveOrPassive"
       class="@(Model.OrderFilter.ActiveOrPassive ? "clicked" : null)" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM