Jquery 动态增加option及获取值 遍历option相关方法

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






猜你喜欢

转载自blog.csdn.net/liq816/article/details/78029367