Jquery 動態增加option及獲取值 遍歷option相關方法
阿新 • • 發佈:2019-02-04
data裡的資料如下圖:
html:
<select id="channel_id" name="channel">
</select>
js:
function getBaseOptionFun(){ $('#channel_id').empty(); $.ajax({ url: "../../ueIndexConfig/getOption.do", type: "POST", data: { province_id:'', channel_id:'' }, async : false, success: function (data) { console.log(data); if(data.all_channel != "" && data.all_channel != null){ for(var i = 0; i < data.all_channel.length; i++){ $("#channel_id").append("<option value='"+data.all_channel[i].channel_id+"'>"+data.all_channel[i].channel_name+"</option>");//新增 } $("#channel_id option:eq(0)").attr('selected', 'selected');//選中第一個 //$("#channel_id").append("<option value=''>請選擇</option>"); } }, fail: function (status) { // 此處放失敗後執行的程式碼 } }); }
獲取select 中選中的值
方法:
//獲取select中值 $("#channel_id option:selected").val(); //獲取select中值channel_id $("#channel_id").val(); //獲取select中文字channel_name $("#channel_id").text(); //$("#channel_id").find("option:selected").text(); //獲取select 中下標值 $("#channel_id").get(0).selectedIndex; //獲取select 最大的index屬性值 $("#channel_id option:last").attr("index");
//select選中索引有好多方式,
$('#someId').find('option:selected').selectedIndex;
$('#someId').find('option:selected').attr('selectedIndex');
這兩種方式取不到索引值
$('#someId').prop('selectedIndex');
$('option:selected', '#someId').index();
$('#someId option').index($('#someId option:selected'))
//以上三種方式可以取到索引值
遍歷option獲取所有值
html:
<select id="channel_id" name="channel" datatype="*" nullmsg="請選擇渠道">
<option value="1" selected="selected">掌上營業廳</option>
<option value="2">網上營業廳</option>
<option value="3">微信營業廳</option>
<option value="8">能力開放平臺</option>
</select>
js:
//方法1:
$(function(){
var array = new Array(); //定義陣列
$("#channel_id option").each(function(){ //遍歷所有option
var channlVal= $(this).val(); //獲取option值
if(channlVal!=''){
array.push(channlVal); //新增到陣列中
}
})
}) ;
//方法2:
var channelArr= new Array();
var channel=$("#channel_id").find("option");
for(var i=0;i<channel.length;i++){
var channlVar=channl.eq(i).val();//option中的值
channelArr.push(channlVar);//新增到陣列中
}
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