简体   繁体   English

如何一键取消选中单选按钮

[英]How do i uncheck radio button in one click

I have the code to uncheck radio button, but the problem is, its not happening in one click when the radio button is checked, I am fetching the value of radio button as checked from mysql, so the default value of radio button is checked and when I click on the radio button the value should uncheck upon single click but my code is making it happen on double click.我有取消选中单选按钮的代码,但问题是,当单选按钮被选中时,它不会在单击时发生,我正在从 mysql 中获取单选按钮的值,因此选中单选按钮的默认值并当我单击单选按钮时,单击时应取消选中该值,但我的代码使其在双击时发生。 How do I make it happen with single click?如何通过单击实现它?

 var check; $('input[type="radio"]').hover(function() { check = $(this).is(':checked'); }); var checkedradio; function docheck(thisradio) { if (checkedradio == thisradio) { thisradio.checked = false; checkedradio = null; } else {checkedradio = thisradio;} }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="radio" name="check" value="check" onClick="javascript:docheck(this);" checked="checked"/>

Radios by design are meant to be used in a group ( https://html.spec.whatwg.org/#radio-button-state-(type=radio) ) - a group of 2 or more radios should form a group to allow the user to pick a value from the selection in that group.收音机的设计旨在用于一组( https://html.spec.whatwg.org/#radio-button-state-(type=radio) ) - 一组 2 个或更多收音机应组成一个组允许用户从该组中的选择中选择一个值。 By design the radio group behaviour is this - once a selection is made (either by the user or programatically), that choice sticks, and there is no way to undo it, other than choose another radio option from the group.根据设计,无线电组的行为是这样的 - 一旦做出选择(由用户或以编程方式),该选择就会保持不变,并且除了从组中选择另一个无线电选项之外,没有办法撤消它。 You'll see in your example, that without the JavaScript bit, if you by default uncheck the radio, then check it manually, you won't be able to uncheck it again.您将在示例中看到,如果没有 JavaScript 位,如果您默认取消选中收音机,然后手动检查,您将无法再次取消选中它。 This is how it's supposed to work.这就是它应该如何工作的方式。

The rule of thumb should be that solving a problem on the backend should not come at the expense of the front-end, as it negatively impacts the user-experience, and will cause problems to the user.经验法则应该是在后端解决问题不应该以牺牲前端为代价,因为它会对用户体验产生负面影响,并且会给用户带来问题。 If you for any reason HAVE TO stick with such a bad UX solution, here is a way to hack your radio to act like a checkbox, but it is seriously not advised, and you should change your backend to use checkboxes instead.如果您出于任何原因不得不坚持使用这种糟糕的 UX 解决方案,这里有一种方法可以让您的收音机像复选框一样工作,但不建议这样做,您应该更改后端以使用复选框。

Here is the radio hack (and a native checkbox input that should be used instead):这是无线电黑客(以及应该使用的本机复选框输入):

 var myRadio = $('input[type="radio"]:checked'); myRadio.on('click', function() { if (myRadio.attr('checked')) { myRadio.removeAttr('checked'); myRadio.prop('checked', false); } else { myRadio.attr('checked', 'checked'); myRadio.prop('checked', true); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <b>This works, but it's bad UX, so avoid!</b><br> <input type="radio" name="check" value="check" checked /> <hr> <b>Use this instead!</b> <br> <input type="checkbox" name="real-check" value="real-check" checked />

You'll see that the jQuery selector is deliberately set to only pick the "checked" radio, so the JavaScript solution only takes over the native behaviour if the radio is checked by default.您会看到 jQuery 选择器被故意设置为仅选择“已检查”无线电,因此 JavaScript 解决方案仅在默认情况下检查无线电时才接管本机行为。 As soon as the radio is not checked by default, you'll see how the browser forces your selection once it's checked manually - this is a tell tale sign that you're trying to deviate from the expected behaviour.只要默认情况下不检查收音机,您就会看到浏览器在手动检查后如何强制您选择 - 这是一个明显的迹象,表明您正试图偏离预期的行为。

You'll also see that the checkbox natively works - without the need for JavaScript or jQuery.您还将看到该复选框本身有效 - 无需 JavaScript 或 jQuery。

RobertP raised an interesting point about the user experience, or in IT-talk: "UX". RobertP 提出了一个关于用户体验的有趣观点,或者在 IT 谈话中:“UX”。 In some cases it is mandatory that a single option needs to be clicked.在某些情况下,必须单击单个选项。 This is exactly what radio buttons were made for.这正是单选按钮的用途。 However, I have come across cases, where a "none" selection should also be offered.但是,我遇到过一些情况,也应该提供“无”选项。 For these cases you could simply supply an extra radio button with the option "none" OR you could make the radio buttons "unselectable" again.对于这些情况,您可以简单地提供一个带有“无”选项的额外单选按钮,或者您可以再次使单选按钮“不可选择”。 This seems to go against the intended radio button behaviour. go 似乎与预期的单选按钮行为相反。 However, as it is possible to start out with no radio buttons being selected, why should it not be possible to return to this state after, maybe, the user had clicked on an item prematurely?然而,既然可以在没有选择单选按钮的情况下开始,为什么在用户过早地点击一个项目之后就不能返回到这个 state 呢?

So, with these considerations in mind I went ahead and put together a way of doing what OP had in mind.因此,考虑到这些考虑,我继续并提出了一种执行 OP 的想法的方法。 I extended the example a little bit by including further radio button options:我通过包含更多单选按钮选项对示例进行了一些扩展:

 $.fn.RBuncheckable=function(){ // simple jQuery plugin const rb=this.filter('input[type=radio]'); // apply only on radio buttons... rb.each(function(){this.dataset.flag=$(this).is(':checked')?1:''}).on('click',function(){ if (this.dataset.flag) $(this).prop('checked',false) // uncheck current // mark whole group (characterised by same name) as unchecked: else rb.filter('[name='+this.name+']').each(function(){this.dataset.flag=''}); this.dataset.flag=this.dataset.flag?'':1; // invert flag for current }); return this; } $('input').RBuncheckable(); // apply it to all radio buttons on this page...
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h4>Two groups of radio buttons with "uncheck" option:</h4> <input type="text" value="This input field is unaffected"> <p>group one:</p> <label><input type="radio" name="check" value="a" checked /> Option A</label><br> <label><input type="radio" name="check" value="b"/> Option B</label><br> <label><input type="radio" name="check" value="c"/> Option C</label> <p>group two:</p> <label><input type="radio" name="second" value="d"/> Option D</label><br> <label><input type="radio" name="second" value="e"/> Option E</label><br> <label><input type="radio" name="second" value="f" checked/> Option F</label>

In the .each() loop I collect the initially checked state for all selected radio buttons..each()循环中,我为所有选定的单选按钮收集最初检查的 state。 I store the individual checked state in a data attribute "flag" for each radio button.我将单个选中的 state 存储在每个单选按钮的数据属性“标志”中。

The click event handler function then picks up this data flag and decides whether to step into action by either removing the checked state from the current element or simply resetting the flag data-attributes for the whole group (characterised by having the same name as the currently clicked one). click事件处理程序 function 然后拾取此数据标志并决定是否通过从当前元素中删除选中的 state 或简单地重置整个组的标志数据属性(特征name与当前点击一个)。 In a last operation it then inverts the flag state for the current element again.在最后一个操作中,它再次反转当前元素的标志 state。 As all data attributes are stored as strings, the values 1 and "" are "truthy" and "falsy" values that can be directly tested.由于所有data属性都存储为字符串,因此值1和“”是可以直接测试的“真”和“假”值。

This results in exactly the behaviour you were looking for.这会导致您正在寻找的行为。 I hope;-)我希望;-)

By having the functionality packaged in a little jQuery plugin it can now be applied to any jQuery object directly.通过将功能打包在一个小 jQuery 插件中,它现在可以直接应用于任何 jQuery object。

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

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