前端设计:jquery操作select 方法大全

摘要: 在前段HTML页面设计中select 下拉框,或者 在 multiple="multiple" 时,表现为列表。经常会在页面上对其进行操作,这些操作不外乎:1. 得到选中的 select 的 option 的值或者text.2. 删除选中的 select 的 option.3. 向select中增加新的option.4. 得到select option 长度,也就是个数size

在前段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("");   //为Select追加一个Option(下拉项)   
$("#select_id").prepend("");   //为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

上一篇: django 事务小结(ORM 事务以及raw sql,customize sql 事务处理)
下一篇: input 输入框在获取焦点与失去焦点时提示的消失与显示
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号