国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > jscript > Javascript实现RadioButtonList取消选择功能

Javascript实现RadioButtonList取消选择功能

来源:程序员人生   发布时间:2014-06-07 10:33:21 阅读次数:3677次

  网(LieHuo.Net)教程 最近在做项目的时要实现单项选择的功能,用RadioButtonList刚好可以实现。但是遗憾的是RadioButtonList选择后不能取消。所以自己用Javascript来实现取消选择的功能。

  首先,定义一个全局的数组变量,保存选择状态。

以下为引用的内容:
//保存各选项选择的状态
var arrayChecked = new Array();

  然后,注册 onload="InitChecked()"事件 ,初始化数组。这一步的目的在于加载原来已经保存过的选项时,保证其状态为选中。

以下为引用的内容:
//初始化选择状态
function InitChecked() {
var controlID = 'radioEmpRole1';
var table = document.getElementById(controlID);
if (table) {
radioButtonList = table.getElementsByTagName('input');
for (var i = 0; i < radioButtonList .length; i++) {
if (radioButtonList .item(i).checked) {
radioButtonList [i] = 1; //被选中
}
else {
radioButtonList [i] = 0; //未被选中
}
}
}
}

  最后,为RadioButtonList注册 onclick="Checked()" 事件,选择选项时根据选项状态和历史状态来决定选项是否被取消选择。 

以下为引用的内容:
//设置选择状态
function Checked() {
var controlID = 'radioEmpRole1';
var table = document.getElementById(controlID);
if (table) {
radioButtonList = table.getElementsByTagName('input');
for (var i = 0; i < radioButtonList .length; i++) {
if (radioButtonList .item(i).checked) { //此次点击,该选项被选中,则判断此选项的历史状态,若也是被选中,则会取消选择。
if (arrayChecked[i] == 1) {
radioButtonList .item(i).checked = false;
arrayChecked[i] = 0;
}
else {
arrayChecked[i] = 1;
}
}
else {
arrayChecked[i] = 0;
}
}
}
}

  通过以上三步,就可以实现点击被选择的选项时会取消选择。

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生