用Javascript实现RadioButtonList的取消选择功能

      最近在做项目的时要实现单项选择的功能,用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;
                    }
                }
            }
        }

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

posted @ 2009-09-08 20:28  完赐  阅读(1532)  评论(0编辑  收藏  举报