A-A+
jquery select操作代码
这里包括jquery获取 select项的个数,索引,前选中项的文本 选中项的值 text的第一项被选中 删除select中选定的项 等操作。
- //得到select项的个数
- jquery.fn.size = function(){
- return jquery(this).get(0).options.length;
- }
- //获得选中项的索引
- jquery.fn.getselectedindex = function(){
- return jquery(this).get(0).selectedindex;
- }
- //获得当前选中项的文本
- jquery.fn.getselectedtext = function(){
- if(this.size() == 0) return "下拉框中无选项";
- else{
- var index = this.getselectedindex();
- return jquery(this).get(0).options[index].text;
- }
- }
- //获得当前选中项的值
- jquery.fn.getselectedvalue = function(){
- if(this.size() == 0)
- return "下拉框中无选中值";
- else
- return jquery(this).val();
- }
- //设置select中值为value的项为选中
- jquery.fn.setselectedvalue = function(value){
- jquery(this).get(0).value = value;
- }
- //设置select中文本为text的第一项被选中
- jquery.fn.setselectedtext = function(text)
- {
- var isexist = false;
- var count = this.size();
- for(var i=0;i<count;i++)
- {
- if(jquery(this).get(0).options[i].text == text)
- {
- jquery(this).get(0).options[i].selected = true;
- isexist = true;
- break;
- }
- }
- if(!isexist)
- {
- alert("下拉框中不存在该项");
- }
- }
- //设置选中指定索引项
- jquery.fn.setselectedindex = function(index)
- {
- var count = this.size();
- if(index >= count || index < 0)
- {
- alert("选中项索引超出范围");
- }
- else
- {
- jquery(this).get(0).selectedindex = index;
- }
- }
- //判断select项中是否存在值为value的项
- jquery.fn.isexistitem = function(value)
- {
- var isexist = false;
- var count = this.size();
- for(var i=0;i<count;i++)
- {
- if(jquery(this).get(0).options[i].value == value)
- {
- isexist = true;
- break;
- }
- }
- return isexist;
- }
- //向select中添加一项,显示内容为text,值为value,如果该项值已存在,则提示
- jquery.fn.addoption = function(text,value)
- {
- if(this.isexistitem(value))
- {
- alert("待添加项的值已存在");
- }
- else
- {
- jquery(this).get(0).options.add(new option(text,value));
- }
- }
- //删除select中值为value的项,如果该项不存在,则提示
- jquery.fn.removeitem = function(value)
- {
- if(this.isexistitem(value))
- {
- var count = this.size();
- for(var i=0;i<count;i++)
- {
- if(jquery(this).get(0).options[i].value == value)
- {
- jquery(this).get(0).remove(i);
- break;
- }
- }
- }
- else
- {
- alert("待删除的项不存在!");
- }
- }
- //删除select中指定索引的项
- jquery.fn.removeindex = function(index)
- {
- var count = this.size();
- if(index >= count || index < 0)
- {
- alert("待删除项索引超出范围");
- }
- else
- {
- jquery(this).get(0).remove(index);
- }
- }
- //删除select中选定的项
- jquery.fn.removeselected = function()
- {
- var index = this.getselectedindex();
- this.removeindex(index);
- }
- //清除select中的所有项
- jquery.fn.clearall = function()
- {
- jquery(this).get(0).options.length = 0;
- }