简体   繁体   English

无法取消选择单选按钮?

[英]Cannot deselect radio button?

I have been attempting to allow radio buttons to be deselected using jQuery, but I am running into issues with the prop function.我一直在尝试允许使用 jQuery 取消选择单选按钮,但我遇到了prop函数的问题。 When this code runs, my conditional ( $(e.currentTarget).prop('checked') ) always evaluates to true.当这段代码运行时,我的条件( $(e.currentTarget).prop('checked') )总是评估为真。

Here is a fiddle which demonstrates my issue: Jsfiddle这是一个演示我的问题的小提琴: Jsfiddle

FYI: I am using jQuery 1.8.2, and I cannot update it because it is a legacy project with many dependencies.仅供参考:我使用的是 jQuery 1.8.2,我无法更新它,因为它是一个具有许多依赖项的遗留项目。 Also, I MUST use radio buttons per the client's request.此外,我必须根据客户的要求使用单选按钮。

Javascript: Javascript:

$("input[name=optionMedia]").click(function(e) {
    if ($(e.currentTarget).prop('checked')) {
        $(e.currentTarget).prop('checked', false);
    }
});

Html:网址:

<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1"/>
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />

You can do it like this你可以这样做

 $('input.bigSizeInput').mouseup(function() { if ($(this).is(':checked')) { setTimeout(function() { $('input.bigSizeInput:checked').prop('checked', false); }, 1) } })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1" /> <input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />

This is because checked is a property.这是因为checked 是一个属性。 If its there it is true, if its not it is not true.如果它在那里它是真的,如果它不在那里它不是真的。 Hence you either should switch to a checkbox or use因此,您应该切换到复选框或使用

$("..").removeProp('checked')

Using checkbox to check/uncheck is better than radio button.使用复选框来选中/取消选中比单选按钮更好。 But if you want to use radio button, you need to check if radio is checked, copy it using and remove checked attribute of copied element and then insert it after target radio.但是如果你想使用单选按钮,你需要检查单选是否被选中,使用并删除复制元素的已选中属性,然后将其插入到目标单选之后。 At the end remove original radio.最后取下原来的收音机。

 $(document).on("mousedown", "input[name=optionMedia]", function(e) { if (this.checked) $(this).clone().prop('checked', false).insertAfter(this).end().remove(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1"/> <input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />

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

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