简体   繁体   English

单选按钮onclick返回false从另一个单选按钮中删除选中的对象

[英]radio button onclick return false remove the checked from the other radio button

I have radio button. 我有单选按钮。 I want that onClick on the radio button It will return false. 我希望onClick在单选按钮上它将返回false。 What that happend is that the radio that i change is not checked and it is good . 发生的事情是我更换的收音机没有检查,而且很好。 but the other radio button that was checked before. 但是之前检查过的另一个单选按钮。 is not checked too. 也没有检查。 here the code: 这里的代码:

 function disableClick(e) { e.preventDefault(); return false; } 
 <input id="fmale" type="radio" name="gender" value="1" checked="checked" onclick="return disableClick(event);"> <input id="male" type="radio" name="gender" value="2" onclick="return disableClick(event);"> 

addEventListener can help you addEventListener可以帮助您

 function disableClick(e) { e.target.checked = false; // clear current radio button e.preventDefault(); return false; } document.getElementById("fmale").addEventListener("click",disableClick) document.getElementById("male").addEventListener("click",disableClick) 
 <input id="fmale" type="radio" name="gender" value="1" checked="checked" /> <input id="male" type="radio" name="gender" value="2"> 

'e.preventDefault()'和'return false'阻止检查下一个单选按钮。

e.preventDefault does not prevent the radio button's attribute checked from being set to true . e.preventDefault不会阻止checked单选按钮的属性设置为true You can console.log(e.target.checked) to see it's set true , even though e.preventDefault() prevents it from visually showing as checked. 您可以console.log(e.target.checked)看到它设置为true ,即使e.preventDefault()阻止它以可视形式显示为选中状态。

The below demo allows the other radio button to automatically be set to checked = false , but then sets the currently clicked on radio to false as well. 下面的演示允许将其他单选按钮自动设置为checked = false ,然后还将当前单击的单选按钮也设置为false

I'm not sure why you want to do this, but here you go 我不确定为什么要这样做,但是您去了

Solution

 $('#fmale').click(function(e) { e.target.checked = false; }); $('#male').click(function(e) { e.target.checked = false; }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="fmale" type="radio" name="gender" value="1" checked="checked"> <input id="male" type="radio" name="gender" value="2"> 

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

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