欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-01 21:50:52
本文实例讲述了jquery操作select常见方法。分享给大家供大家参考,具体如下: 在前段html页面设计中select 下拉框,或者 在 multiple="mult...

本文实例讲述了jquery操作select常见方法。分享给大家供大家参考,具体如下:

在前段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选择器用法总结

希望本文所述对大家jquery程序设计有所帮助。