select標籤的陷阱

14.select框的選中jquery

誤區:ajax

          一直覺得jquery獲取select中option被選中的文本值,是這樣寫的:async

          $("#s").text();  //獲取全部option的文本值spa

實際上應該這樣:code

          $("#s option:selected").text();  //獲取選中的option的文本值索引

獲取select中option的被選中的value值,rem

           $("#s").val();get

           $("#s option:selected").val();io

讓select中value爲某一值的option被選中select

        $("#s").find("option[value='xx']").attr("selected",true);

若是沒有生效則換成:

$('#s').val(saveValue).trigger('change');

若是是用ajax動態添加option的話,以上的方法也會行不通,把async設置成false就能夠了。

其中saveValue爲value值。

js獲取select選中的值:

          var sel=document.getElementById("select1"); 

          var index = sel.selectedIndex; // 選中索引

          albumid= sel.options[index].value;//要的值

刪除select下的option:

$("#s").options.length=0;     $("#s").options.remove(index),index爲必須

獲取select下option的個數:$("#s")[0].options.length

相關文章
相關標籤/搜索