1. 程式人生 > >js、jquery、動態新增option項

js、jquery、動態新增option項

JS:

var selid = document.getElementById("sltid");

       for(var i=0; i<10;i++){     //迴圈新增多個值

              sid.option[i] = new Option(i,i);

       }

       sid.options[sid.options.length]=new Option("1","2");   // 在最後一個值後面新增多一個

JQuery:

<select id="aa"></select>
1.jQuery("<option value='1'>abc</option>").appendTo("#aa");

2.jQuery("<option></option>").attr({val:"1",text:"abc"}).appendTo("#aa");

3.jQuery("<option></option>").val("1").text("abc").appendTo("#aa");
4.$("#selectId").append("<option value='"+value+"'>"+text+"</option>");


當然除了這幾句,還有設定預設選擇值、第一個的值、最後一個的值、第N個的值等等的,所以在網上搜了一上:

jQuery獲取Select選擇的Text和Value:

$("#select_id").change(function(){//code...});   //為Select新增事件,當選擇其中一項時觸發

var checkText=$("#select_id").find("option:selected").text();  //獲取Select選擇的Text

var checkValue=$("#select_id").val();  //獲取Select選擇的Value

var checkIndex=$("#select_id ").get(0).selectedIndex;  //獲取Select選擇的索引值

var maxIndex=$("#select_id option:last").attr("index");  //獲取Select最大的索引值


jQuery新增/刪除Select的Option項:

1. $("#select_id").append("<option value='Value'>Text</option>");  //為Select追加一個Option(下拉項)

2. $("#select_id").prepend("<option value='0'>請選擇</option>");  //為Select插入一個Option(第一個位置)

3. $("#select_id option:last").remove();  //刪除Select中索引值最大Option(最後一個)

4. $("#select_id option[index='0']").remove();  //刪除Select中索引值為0的Option(第一個)

5. $("#select_id option[value='3']").remove();  //刪除Select中Value='3'的Option

5. $("#select_id option[text='4']").remove();  //刪除Select中Text='4'的Option