獲取和設置select的選中項的值

<!DOCTYPE html>

<html>

<head lang="en">

    <meta charset="UTF-8">

    <title>獲取select的選中項的值</title>

</head>

<body>

<select id="select0">

    <option value="0">請選擇選項</option>

    <option value="1">選項一</option>

    <option value="2">選項二</option>

    <option value="3">選項三</option>

    <option value="4">選項四</option>

    <option value="5">選項五</option>

</select>

</body>

</html>

<script src="jquery-2.1.1.min.js"></script>

<script>

    window.onload=function(){

        var tags=document.getElementsByTagName("select");

        //通過javascript來獲取select的選中項【】

        var s=document.getElementById("select0");

        s.selectedIndex=2;//設置選中項的索引

        var index= s.selectedIndex;//獲取選中項的索引

        console.log(s.options[index].value);//輸出選中項的值:value=3

        console.log(s.options[index].text);//輸出選中項的option裏面的值:選項三

        //通過下面方法也可以獲取下面的值

        var selectedValue=document.getElementById("select0").value;

        console.log(selectedValue);


        //通過jquery方法去設置和獲取

        console.log($("#select0").find("option:selected").text());//得到選中的option的裏面的text

        console.log($("#select0").val());//得到選中的值

        $("#select0").val(1);//設置選中的值

        console.log($("#select0").val());


        //jquery和javascript的結合使用

        var sIndex=$("#select0").get(0).selectedIndex;

        //根據text=‘選項四’,來選中該項

        $("#select0 option[text='選項一']").attr("selected","true");


        $("#select0 option[value='2']").remove();//刪除value='2'的選項刪除

        //把除了第一項的其他項都刪除

        $("#select0 option[value!='0']").remove();//可用於在多個選擇框相互關聯,然後當其中一個選項框開始選中時,清空另一個選項框。

    };

</script>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章