jquery 获取 combo box 中的值

Combox box 的取值问题, 乐意黎原创。

$("option:selected").attr("name");

$("option:selected").data("id");

$('option').attr('name');
$('option').attr('data-id');

取得当前选中option的属性还可以用这个:$("#selroom").find(" option:selected").attr("status");
$("#selroom").change(function () {
     alert($("#selroom option:selected").attr("status"));
 });
$("#select的id").val()
或者

$("#select的id>option:selected").val()


jQuery获取Select元素,并选择的Text和Value: 

复制代码代码如下:

$("#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的项选中 

jQuery添加/删除Select元素的Option项: 

实例分析: 
复制代码代码如下:

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

三级分类 <select name="thirdLevel" id="thirdLevel" 
οnchange="getFourthLevel()"> 
<option value="0" id="thirdOption"> 
请选择三级分类 
</option> 
</select> 
</div> 

四级分类: 
<select name="fourthLevelId" id="fourthLevelId"> 
<option value="0" id="fourthOption"> 
请选择四级分类 
</option> 
</select> 
</div> 
if($("#thirdLevel").val()!=0){ 
$("#thirdLevel option[value!=0]").remove(); 

if($("#fourthLevelId").val()!=0){ 
$("#fourthLevelId option[value!=0]").remove(); 
}//这个表示:假如我们希望当选择选择第三类时:如果第四类中有数据则删除,如果没有数据第四类的商品中的为默认值。在后面学习了AJAX技术后经常会使用到! 

获取Select : 
获取select 选中的 text : 
$("#ddlRegType").find("option:selected").text(); 
获取select选中的 value: 

$("#ddlRegType ").val(); 

获取select选中的索引: 
$("#ddlRegType ").get(0).selectedIndex; 
设置select: 
设置select 选中的索引: 
$("#ddlRegType ").get(0).selectedIndex=index;//index为索引值 

设置select 选中的value: 
复制代码代码如下:

$("#ddlRegType ").attr("value","Normal“); 
$("#ddlRegType ").val("Normal"); 
$("#ddlRegType ").get(0).value = value; 

设置select 选中的text: 
复制代码代码如下:

var count=$("#ddlRegType option").length; 
for(var i=0;i<count;i++) 
{ if($("#ddlRegType ").get(0).options[i].text == text) 

$("#ddlRegType ").get(0).options[i].selected = true; 
break; 



$("#select_id option[text='jQuery']").attr("selected", true); 

设置select option项: 
复制代码代码如下:

$("#select_id").append("<option value='Value'>Text</option>"); //添加一项option 
$("#select_id").prepend("<option value='0'>请选择</option>"); //在前面插入一项option 
$("#select_id option:last").remove(); //删除索引值最大的Option 
$("#select_id option[index='0']").remove();//删除索引值为0的Option 
$("#select_id option[value='3']").remove(); //删除值为3的Option 
$("#select_id option[text='4']").remove(); //删除TEXT值为4的Option 

清空 Select: 

$("#ddlRegType ").empty(); 

jquery获得值: 

val() 
text() 

设置值 
val('在这里设置值') 
复制代码代码如下:

$("document").ready(function(){ 
$("#btn1").click(function(){ 
$("[name='checkbox']").attr("checked",'true');//全选 
}) 
$("#btn2").click(function(){ 
$("[name='checkbox']").removeAttr("checked");//取消全选 
}) 
$("#btn3").click(function(){ 
$("[name='checkbox']:even").attr("checked",'true');//选中所有奇数 
}) 
$("#btn4").click(function(){ 
$("[name='checkbox']").each(function(){//反选 
if($(this).attr("checked")){ 
$(this).removeAttr("checked"); 

else{ 
$(this).attr("checked",'true'); 

}) 
}) 
$("#btn5").click(function(){//输出选中的值 
var str=""; 
$("[name='checkbox'][checked]").each(function(){ 
str+=$(this).val()+"\r\n"; 
//alert($(this).val()); 
}) 
alert(str); 
}) 
}) 




假如有这么一个select

1
2
3
4
< select  id = "sel" >
         < option  value = "1"  id = "id1" >www.aerchi.com</ option >
         < option  value = "2"  id = "id2" >www.luxi.ren</ option >
     </ select >

调用:

1
alert($( ":selected" , "#sel" ).attr( "id" ));

即可

$("#thisselectID option:selected").attr("id");



是这样的. 这是前端代码.
XML/HTML code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
< tr >
                     < td  class = "tdal" >&nbsp所属部门:
                     </ td >
 
                     < td  class = "tdar" >
                         < select  id = "ipt_section"  class = "easyui-combobox"  name = "ipt_section"  editable = "false" >
                             < option  value = "0" >采矿部</ option >
                             < option  value = "1" >生产调度科</ option >
                             < option  value = "2" >技术科</ option >
                             < option  value = "3" >综合办</ option >
                             < option  value = "4" >党群工作室</ option >
                             < option  value = "5" >机电维修部</ option >
                             < option  value = "6" >储运部</ option >
                         </ select >
                     </ td >
                 </ tr >




初始化datagrid代码

JavaScript code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  $( '#tab_list' ).datagrid({
                 title:  '用户列表' //表格标题
                 url: location.href,   //请求数据的页面 
                 sortName:  'UserFile_id' //排序字段
                 idField:  'UserFile_id' //标识字段,主键
                 iconCls:  '' //标题左边的图标
                 width:  '100%' //宽度
                 height: $(parent.document).find( "#mainPanle" ).height() - 10 > 0 ? $(parent.document).find( "#mainPanle" ).height() - 10 : 500,  //高度
                 nowrap:  false //是否换行,True 就会把数据显示在一行里
                 striped:  true //True 奇偶行使用不同背景色
                 collapsible:  false //可折叠
                 sortOrder:  'desc' //排序类型
                 remoteSort:  true //定义是否从服务器给数据排序
                 frozenColumns: [[ //冻结的列,不会随横向滚动轴移动
                     { field:  'cbx' , checkbox:  true  },
                     { title:  '用户编号' , field:  'UserFile_num' , width: 60, sortable:  true  },
                     { title:  '用户账号名' , field:  'UserFile_name' , width: 100 }
                 ]],
                 columns: [[
                     { title:  '密码' , field:  'UserFile_pwd' , width: 120 },
                     { title:  '用户性别' , field:  'UserFile_sex' , formatter:  function  (value, rec, index) {  return  value == 0 ?  '女'  '男'  }, width: 80 },
                     { title:  '所属部门' , field:  'UserFile_section' ,width: 100 },
                      { title:  '职位' , field:  'UserFile_post' , width: 100 },
                       { title:  '电话号码' , field:  'UserFile_telephone' , width: 100 },
                        { title:  '邮箱' , field:  'UserFile_email' , width: 150 },
 
                     {
                         title:  '操作' , field:  'UserFile_id' , width: 80, formatter:  function  (value, rec) {
                             return  '<a style="color:red" href="javascript:;" onclick="EditData('  + value +  ');$(this).parent().click();return false;">修改</a>' ;
                         }
                     }
                 ]],
                 toolbar:  "#tab_toolbar" ,
                 queryParams: {  "action" "query"  },
                 pagination:  true //是否开启分页
                 pageNumber: 1,  //默认索引页
                 pageSize: 10,  //默认一页数据条数
                 rownumbers:  true  //行号
             });


添加用户后的前台展示



奇怪的事情出现了.本该职位列 中应该出现 采矿部..为什么显示的全部是数字呢?>





(function ($) {
    $.widget("ui.combobox", {
        _create: function () {
            var self = this,
        select = this.element.hide(),
        selected = select.children(":selected"),
        value = selected.val() ? selected.text() : "",
        regSearch = /^[^a-zA-Z0-9]*([a-zA-Z0-9])/i,
        comboData = select.children("option").map(function () {
            if (this.value ) {
                var text = $(this).text(), 
                    labelHtml = self.options.label ? self.options.label(this) : text; //allows list customization

                return {
                    label: labelHtml,
                    value: text,
                    option: this
                };
            }
        });

            var input = this.input = $("<input type='text' />")
                    .insertAfter(select)
                    .val(value)
                    .keydown( function( event ) {
                    var keyCode = $.ui.keyCode;
                    switch( event.keyCode ) {
                        case keyCode.PAGE_UP:
                        case keyCode.PAGE_DOWN:
                        case keyCode.UP:
                        case keyCode.DOWN:
                        case keyCode.ENTER:
                        case keyCode.NUMPAD_ENTER:
                        case keyCode.TAB:
                        case keyCode.ESCAPE:
                            //let autocomplete handle these
                            break;
                        default:
                            //prevent autocomplete doing anything
                            event.stopImmediatePropagation();
                            //only react to [a-zA-Z0-9]
                            if ((event.keyCode < 91 && event.keyCode > 59)
                                || (event.keyCode < 58 && event.keyCode > 47)) {

                                var str = String.fromCharCode(event.keyCode).toLowerCase(), currVal = input.val(), opt;

                                //find all options whose first alpha character matches that pressed
                                var matchOpt = select.children().filter(function() {
                                    var test = regSearch.exec(this.text);
                                    return (test && test.length == 2 && test[1].toLowerCase() == str);
                                });

                                if (!matchOpt.length ) return false;

                                //if there is something selected we need to find the next in the list
                                if (currVal.length) {
                                    var test = regSearch.exec(currVal);
                                    if (test && test.length == 2 && test[1].toLowerCase() == str) {
                                        //the next one that begins with that letter
                                        matchOpt.each(function(ix, el) {
                                            if (el.selected) {
                                                if ((ix + 1) <= matchOpt.length-1) {
                                                    opt = matchOpt[ix + 1];
                                                }
                                                return false;
                                            }
                                        });
                                    }
                                } 

                                //fallback to the first one that begins with that character
                                if (!opt)
                                    opt = matchOpt[0];

                                //select that item
                                opt.selected = true;
                                input.val(opt.text);

                                //if the dropdown is open, find it in the list
                                if (input.autocomplete("widget").is(":visible")) {
                                    input.data("autocomplete").widget().children('li').each(function() {        
                                        var $li = $(this);
                                        if ($li.data("item.autocomplete").option == opt) {
                                            input.data("autocomplete").menu.activate(event,$li);
                                            return false;
                                        }
                                    });
                                }
                            }
                            //ignore all other keystrokes
                            return false;
                            break;
                        }
                      })
                    .autocomplete({
                        delay: 0,
                        minLength: 0,
                        source: function (request, response) { response(comboData); },
                        select: function (event, ui) {
                            ui.item.option.selected = true;
                            self._trigger("selected", event, {
                                item: ui.item.option
                            });
                        },
                        change: function (event, ui) {
                            if (!ui.item) {                 
                                var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                                    valid = false;
                                select.children("option").each(function () {
                                    if ($(this).text().match(matcher)) {
                                        this.selected = valid = true;
                                        return false;
                                    }
                                });
                                if (!valid) {
                                    // remove invalid value, as it didn't match anything
                                    $(this).val("");
                                    select.val("");
                                    input.data("autocomplete").term = "";
                                    return false;
                                }
                            }
                        }
                    })
                    .addClass("ui-widget ui-widget-content ui-corner-left")
                    .click(function() { self.button.click(); })
                    .bind("autocompleteopen", function(event, ui){
                        //find the currently selected item and highlight it in the list
                        var opt = select.children(":selected")[0];
                        input.data("autocomplete").widget().children('li').each(function() {        
                            var $li = $(this);
                            if ($li.data("item.autocomplete").option == opt) {
                                input.data("autocomplete").menu.activate(event,$li);
                                return false;
                            }
                        });
                    });

            input.data("autocomplete")._renderItem = function (ul, item) {
                return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a href='#'>" + item.label + "</a>")
                    .appendTo(ul);
            };

            this.button = $("<button type='button'> </button>")
                    .attr("tabIndex", -1)
                    .attr("title", "Show All Items")
                    .insertAfter(input)
                    .button({
                        icons: {
                            primary: "ui-icon-triangle-1-s"
                        },
                        text: false
                    })
                    .removeClass("ui-corner-all")
                    .addClass("ui-corner-right ui-button-icon")
                    .click(function () {
                        // close if already visible
                        if (input.autocomplete("widget").is(":visible")) {
                            input.autocomplete("close");
                            return;
                        }

                        // pass empty string as value to search for, displaying all results
                        input.autocomplete("search", "");
                        input.focus();
                    });
        },

        //allows programmatic selection of combo using the option value
        setValue: function (value) {
            var $input = this.input;
            $("option", this.element).each(function () {
                if ($(this).val() == value) {
                    this.selected = true;
                    $input.val(this.text);
                    return false;
                }
            });
        },

        destroy: function () {
            this.input.remove();
            this.button.remove();
            this.element.show();
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);

乐意黎.

本文地址: http://blog.csdn.net/aerchi/article/details/51074810





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值