如何取消选中已选中的单选按钮

时间:2013-06-15 05:42:01

标签: javascript jquery radio-button

这个解决方案只适用于firefox

$(':radio').on("change", function(event) {
  $(this).prop('checked', true);
});

$(':radio').on("click", function(event) {
  $(this).prop('checked', false);
});

在Chrome中,它不允许您选择任何内容 http://jsfiddle.net/wuAWn/

Ofc,我可以使用变量并编写类似

的内容
var val = -1;
$(':radio').on("click", function() {
  if($(this).val() == val) {
    $(this).prop('checked', false);
    val = -1;
  }
  else val = $(this).val();
});

但是我的页面上会有很少的单选按钮组,并且html内容是通过ajax加载的,所以我想为所有这些单元添加1个函数,而不是为每个单选按钮组定义变量并为其写入相同的函数每个单选按钮组。

编辑:感谢您对复选框的帮助,但是对于充当单选按钮组的复选框,您需要编写adittional javascrip,取消选中具有相同名称的所有其他复选框onclick,我已经有单选按钮css,它更容易我只是添加像look-like-checkbox这样的类,让它看起来像复选框,我使用统一的库来自定义外观,无论如何这里是我奇怪的解决方案http://jsfiddle.net/wuAWn/9/

5 个答案:

答案 0 :(得分:37)

这个简单的脚本允许您取消选中已经选中的单选按钮。适用于所有支持JavaScript的浏览器。

var allRadios = document.getElementsByName('re');
var booRadio;
var x = 0;
for(x = 0; x < allRadios.length; x++){
  allRadios[x].onclick = function() {
    if(booRadio == this){
      this.checked = false;
      booRadio = null;
    } else {
      booRadio = this;
    }
  };
}
<input type='radio' class='radio-button' name='re'>
<input type='radio' class='radio-button' name='re'>
<input type='radio' class='radio-button' name='re'>

答案 1 :(得分:10)

单选按钮是必需的选项...如果要取消选中它们,请使用复选框,不需要复杂化并允许用户取消选中单选按钮;删除JQuery允许您从其中一个中选择

答案 2 :(得分:7)

您可以考虑为标有“无”之类的每个组添加一个额外的单选按钮。这可以创建一致的用户体验,而不会使开发过程复杂化。

答案 3 :(得分:3)

试试这个

所有收音机的单一功能都有“单选按钮”

使用chrome和FF

$('.radio-button').on("click", function(event){
  $('.radio-button').prop('checked', false);
  $(this).prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type='radio' class='radio-button' name='re'>
<input type='radio'  class='radio-button' name='re'>
<input type='radio'  class='radio-button' name='re'>

答案 4 :(得分:-1)

试试这个

var radio_button=false;
$('.radio-button').on("click", function(event){
  var this_input=$(this);
  if(this_input.attr('checked1')=='11') {
    this_input.attr('checked1','11')
  } else {
    this_input.attr('checked1','22')
  }
  $('.radio-button').prop('checked', false);
  if(this_input.attr('checked1')=='11') {
    this_input.prop('checked', false);
    this_input.attr('checked1','22')
  } else {
    this_input.prop('checked', true);
    this_input.attr('checked1','11')
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type='radio' class='radio-button' name='re'>
<input type='radio' class='radio-button' name='re'>
<input type='radio' class='radio-button' name='re'>

相关问题