jquery操作select常见方法大全【7种情况】

在前段HTML页面设计中select 下拉框,或者 在 multiple="multiple" 时,表现为列表。经常会在页面上对其进行操作,这些操作不外乎:

1. 得到选中的 select 的 option 的值或者text.
2. 删除选中的 select 的 option.
3. 向select中增加新的option.
4. 得到select option 长度,也就是个数size
5. 清空select.
6. 两个select 框之间互相添加删除,从左边到右边,从右边到左边的操作,通常是多选情况。
7. 判断在 select 框中是否存在某一个值的选项

对第一种情况,用如下方法:

$("#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选择的Text和Value:

$("#select_id ").get(0).selectedIndex=1; //设置Select索引值为1的项选中 $("#select_id ").val(4); //设置Select的Value值为4的项选中 $("#select_id option[text='jQuery']").attr("selected", true); //设置Select的Text值为jQuery的项选中

对第二种情况,删除的处理:

$("#select_id option:last").remove(); //删除Select中索引值最大Option(最后一个) $("#select_id option[index='0']").remove(); //删除Select中索引值为0的Option(第一个) $("#select_id option[value='3']").remove(); //删除Select中Value='3'的Option $("#select_id option[text='4']").remove(); //删除Select中Text='4'的Option

如果要删除选中的option ,则需要先得到 选中option 的序号. var checkIndex=$("#select_id ").get(0).selectedIndex; 然后再调用上面的方法删除.

对第三种情况,增加option 的处理:

$("#select_id").append("<option value='Value'>Text</option>"); //为Select追加一个Option(下拉项) $("#select_id").prepend("<option value='0'>请选择</option>"); //为Select插入一个Option(第一个位置)

对第四种情况,得到select 的长度

var totalcount=$("#single_user_choice").get(0).options.length;

第五种情况,清空select

$("#single_user_choice").get(0).options.length=0;

第六种情况。两个select 框之间互相添加删除,从左边到右边,从右边到左边的操作,通常是多选情况,也就是设置了 multiple="multiple" 。

var $options = $('#select1 option:selected');//获取当前选中的项 var $remove = $options.remove();//删除下拉列表中选中的项 $remove.appendTo('#select2');//追加给对方

第七种情况,判断在select 是否存在某个value  的 option

function is_Exists(selectid,value){ var theid='#'+selectid; var count=$(theid).get(0).options.length; var isExist = false; for(var i=0;i<count;i++){ if ($(theid).get(0).options[i].value == value){ isExist=true; break; } } return isExist; }

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery常见事件用法与技巧总结》、《jQuery常用插件及用法总结》、《jQuery操作json数据技巧汇总》、《jQuery扩展技巧总结》、《jQuery常见经典特效汇总》及《jquery选择器用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/e2deb28d10620720fee29528988fca19.html