1. 程式人生 > >js和jq判斷select是否選中、獲取select選中的值

js和jq判斷select是否選中、獲取select選中的值

JS部分

var   mySelect = document.getElementById(”testSelect”);//定位id(獲取select)

var   index =mySelect.selectedIndex;// 選中索引(選取select中option選中的第幾個)

var   text =mySelect.options[index].text; // 選中文字

var   value =mySelect.options[index].value; // 選中值

mySelect.options[index].selected // 判斷select中的某個option是否選中   true為選中   false 為未選中

  1. if(mySelect.options[1].selected == true){

  2. console.log(1)

  3. }

JQ部分

1.判斷option是否被選中

$("#id").is(":checked")//為false時是未被選中的,為true時是被選中

$("#id").attr('checked')==undefined//為false時是未被選中的,為true時是被選中

2.獲取select選中的值

$("#mySelect option:selected").text()

$("#mySelect").find('option:selected').text()

$("#mySelect").val();

3.獲取select選中的索引

$("#mySelect").get(0).selectedindex

4.新增option

$("#mySelect").append("<option value="+value+">"+text+"<option>");

5.刪除option

$("#myOption").remove()