如何取消选中已选中的单选按钮 [英] How to uncheck checked radio button

查看:155
本文介绍了如何取消选中已选中的单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是这个解决方案仅适用于firefox

The thing is this solution work only in firefox

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

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

在chrome中,它不会允许你选择任何
http://jsfiddle.net/wuAWn/

In chrome, it wont allow you to select anything http://jsfiddle.net/wuAWn/

Ofc,我可以使用变量并写出像

Ofc, i could use variable and write something like

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

但我的页面上会有几个单选按钮组,而html内容是通过ajax加载的,所以我我想为所有这些功能提供1个功能,而不是为每个单选按钮组定义变量,并为每个单选按钮组编写相同的功能。

But i will have few radio button groups on my page and html content is loaded through ajax, so i would like to wrtite 1 function for all of them, instead of defining variables for every one radio button group and write same function for every radio button group.

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

thanks for your help with checkboxes, but for checkboxes to act as a radio button group, you need to write adittional javascrip that will uncheck all other checkboxes with same name onclick, i have already radio button css and its easier for me just to add class like look-like-checkbox and make it look like checkbox, i use uniform library for custom look, anyway here is my weird solution http://jsfiddle.net/wuAWn/9/

推荐答案

这个简单的脚本可以让你取消选中选中单选按钮。适用于所有支持JavaScript的浏览器。

This simple script allows you to uncheck an already checked radio button. Works on all javascript enabled browsers.

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'>

这篇关于如何取消选中已选中的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆