JavaScript操作Select

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <select name="bigclass" id="bigclass" onchange="javascript:updatePage2();">
            <option value="1" selected="selected">java</option>
            <option value="2">asp.net</option>
            <option value="3">php</option>
            <option value="4">c++</option>
            <option value="5">delphi</option>
        </select>
        <input type="button" onclick="Test()" value="测试" />
    </div>
    </form>
</body>
</html>

<script language="javascript" type="text/javascript">

    function Test() {
        //一.获取text值
        var text = document.getElementById("bigclass").options[window.document.getElementById("bigclass").selectedIndex].text;
        alert('text:' + text);

        //二.获取value值
        var val = window.document.getElementById("bigclass").value;
        alert('val:' + val);

        //三.获取select分配的索引值
        var idx = window.document.getElementById("bigclass").selectedIndex;
        alert('idx:' + idx);

        //四.新增一个option
        var sel = document.getElementById("bigclass");
        var op = document.createElement("option");
        op.value = 3;
        op.text = 'php';
        sel.add(op);
        alert('新增option成功!');

        //五.删除一个option
        var sel = document.getElementById("bigclass");
        if (sel.selectedIndex == -1) {
            alert("请选中要删除的项!");
        }
        for (var i = 0; i < sel.options.length; i++) {
            if (sel.options[i].selected) {
                sel.options.remove(i);
                break;
            }
        }
        alert('删除当前option成功!');

        //六.清空select的所有option
        var citySel = document.getElementById("bigclass");
        citySel.options.length = 0;
        alert('清空所有option成功!');

        //七.设置select的当前选中项
        //方法1(单个select):
        document.getElementById("products_type_id").selectedIndex = 1;
        //方法2(级联select如省市级联):
        var province_sel = document.getElementById("province"); //获得省select
        var city_sel = document.getElementById("city"); //获得市select
        for (var i = 0; i < province_sel.options.length; i++) {
            if (province_sel.options[i].value == "从数据库获取的省的值") {
                province_sel.options[i].selected = true;
                break;
            }
        }
        initCity("从数据库获取的省的值"); //初始化市select
        for (var i = 0; i < city_sel.options.length; i++) {
            if (city_sel.options[i].value == "${city}") {
                city_sel.options[i].selected = true;
                break;
            }
        }

        //八.创建select动态设置选中项
        var sel = document.getElementById("other_state");
        var sel_val = document.getElementById("other_media_id").innerHTML;
        for (var obj in data) {
            var id = data[obj]["other_media_id"];
            var name = data[obj]["other_media_name"];
            var op = document.createElement_x("option");
            op.setAttribute("value", id);
            op.appendChild(document.createTextNode(name));
            if (id == sel_val) {
                op.setAttribute("selected", "true");
            }
            sel.appendChild(op);
        }

        //1、向Select里添加Option
        function fnAddItem(text, value) {
            var selTarget = document.getElementById("selID");
            selTarget.Add(new Option("text", "value"));
        }

        //2、删除Select里的Option
        function fnRemoveItem() {
            var selTarget = document.getElementById("selID");
            if (selTarget.selectedIndex > -1) {//说明选中
                for (var i = 0; i < selTarget.options.length; i++) {
                    if (selTarget.options[i].selected) {
                        selTarget.remove(i);
                        i = i - 1; //注意这一行
                    }
                }
            }
        }

        //3、移动Select里的Option到另一个Select中
        function fnMove(fromSelectID, toSelectID) {
            var from = document.getElementById(fromSelectID);
            var to = document.getElementById(toSelectID);
            for (var i = 0; i < from.options.length; i++) {
                if (from.options[i].selected) {
                    to.appendChild(from.options[i]);
                    i = i - 1;
                }
            }
        }
        //if 里的代码也可用下面几句代码代替
        //var op = from.options[i];
        //to.options.add(new Option(op.text, op.value));
        //from.remove(i);
       
        //4、Select里Option的上下移动
        function fnUp() {
            var sel = document.getElementById("selID");
            for (var i = 1; i < sel.length; i++) {//最上面的一个不需要移动,所以直接从i=1开始
                if (sel.options[i].selected) {
                    if (!sel.options.item(i - 1).selected) {//上面的一项没选中,上下交换
                        var selText = sel.options[i].text;
                        var selValue = sel.options[i].value;
                        sel.options[i].text = sel.options[i - 1].text;
                        sel.options[i].value = sel.options[i - 1].value;
                        sel.options[i].selected = false;
                        sel.options[i - 1].text = selText;
                        sel.options[i - 1].value = selValue;
                        sel.options[i - 1].selected = true;
                    }
                }
            }
        }
        //在进行上下两项互换时,也可以使用以下代码,但是效率很低,因为每一次的Dom操作都将导致整个页面的重新布局,所以不如直接修改元素的属性值。
        //                        var oOption = sel.options[i]
        //                        var oPrevOption = sel.options[i-1]
        //                        sel.insertBefore(oOption,oPrevOption);
        //向下移动同理
        function fnDown() {
            var sel = fnGetTarget("selLeftOrRight");
            for (var i = sel.length - 2; i >= 0; i--) {//向下移动,最后一个不需要处理,所以直接从倒数第二个开始
                if (sel.options.item(i).selected) {
                    if (!sel.options.item(i + 1).selected) {//下面的Option没选中,上下互换
                        var selText = sel.options.item(i).text;
                        var selValue = sel.options.item(i).value;
                        sel.options.item(i).text = sel.options.item(i + 1).text;
                        sel.options.item(i).value = sel.options.item(i + 1).value;
                        sel.options.item(i).selected = false;
                        sel.options.item(i + 1).text = selText;
                        sel.options.item(i + 1).value = selValue;
                        sel.options.item(i + 1).selected = true;
                    }
                }
            }
        }

        //5、Select里Option的排序
        //这里借助Array对象的sort方法进行操作,sort方法接受一个function参数,可以在这个function里定义排序时使用的算法逻辑。
        //array.sort([compareFunction]) 里compareFunction接受两个参数(p1,p2),sort操作进行时,array对象会每次传两个值进去,进行比较;compareFunciton必须返回一个整数值:当返回值>0时,p1会排在p2后面;返回值<0时,p1会排在p2前面;返回值=0时,不进行操作。
        //例如:
        function fnCompare(a, b) {
            if (a < b)
                return -1;
            if (a > b)
                return 1;
            return 0;
        }

        var arr = new Array();
        //add some value into arr
        arr.sort(fnCompare);
        //这里sort的操作结果就是arr里的项按由小到大的升序排序
        //如果把fnCompare里改为
        //if (a < b)
        // return 1;
        //if (a > b)
        // return -1;
        //return 0;
        //则sort的结果是降序排列
        //好,下面就是对Select里Option的排序
        //因为排序可以按Option的Value排序,也可以按Text排序,这里只演示按Value排序

        function sortItem() {
            var sel = document.getElementById("selID");
            var selLength = sel.options.length;
            var arr = new Array();
            var arrLength;
            //将所有Option放入array
            for (var i = 0; i < selLength; i++) {
                arr[i] = sel.options[i];
            }
            arrLength = arr.length;
            arr.sort(fnSortByValue); //排序
            //先将原先的Option删除
            while (selLength--) {
                sel.options[selLength] = null;
            }
            //将经过排序的Option放回Select中
            for (i = 0; i < arrLength; i++) {
                sel.add(new Option(arr[i].text, arr[i].value));
            }
        }

        function fnSortByValue(a, b) {
            var aComp = a.value.toString();
            var bComp = b.value.toString();
            if (aComp < bComp)
                return -1;
            if (aComp > bComp)
                return 1;
            return 0;
        }
        //排序时还可以有更多选项,比如将value值看做Integer或是String进行排序,得到的结果是不一样的。
    }

</script>

posted on 2011-03-11 16:29  啊.辉  阅读(5925)  评论(0编辑  收藏  举报

导航