现在的位置: 首页 > 综合 > 正文

jquery操作select(取值,设置选中)

2018年01月24日 ⁄ 综合 ⁄ 共 1907字 ⁄ 字号 评论关闭

每一次操作select的时候,总是要出来翻一下资料,不如自己总结一下,以后就翻这里了。

比如<select class="selector"></select>

1、设置value为pxx的项选中

     $(".selector").val("pxx");

2、设置text为pxx的项选中

    $(".selector").find("option[text='pxx']").attr("selected",true);

    这里有一个中括号的用法,中括号里的等号的前面是属性名称,不用加引号。很多时候,中括号的运用可以使得逻辑变得很简单。

3、获取当前选中项的value

    $(".selector").val();

4、获取当前选中项的text

    $(".selector").find("option:selected").text();

    这里用到了冒号,掌握它的用法并举一反三也会让代码变得简洁。

 

补充:很多时候用到select的级联,即第二个select的值随着第一个select选中的值变化。这在jquery中是非常简单的。

如:$(".selector1").change(function(){

     // 先清空第二个

      $(".selector2").empty();

     // 实际的应用中,这里的option一般都是用循环生成多个了

      var option = $("<option>").val(1).text("pxx");

      $(".selector2").append(option);

});

5、获取下拉列表中所有的option

var sle = document.getElementById("selCmp").option;

for (var i=0;i<sel.length;i++) {
alert(se[i].text + ";" + se[i].value);

}

6、清空 Select:
 1>. $("#cusChildTypeId").empty();
 2>. $("#cusChildTypeId").get(0).options.length = 0; 

7、删除select中值为value的项 
        var count = $("#cusChildTypeId").size();           
        for(var i=0;i<count;i++)   
        {   
            if($("#cusChildTypeId").get(0).options[i].value == value)   
            {   
                $("#cusChildTypeId").get(0).remove(i);   
                break;   
            }
        }

8、向select中添加一项,显示内容为text,值为value   
 $("#cusChildTypeId").get(0).options.add(new Option(text,value));

9、获取select选中的索引:
      $("#ddlRegType ").get(0).selectedIndex;

10、得到select项的个数   
 $("#cusChildTypeId").get(0).options.length

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

12、设置select 选中的value:
    $("#cusChildTypeId").attr("value","Normal");
    $("#cusChildTypeId").val("Normal");
    $("#cusChildTypeId").get(0).value = "Normal";

13、设置select 选中的text:
 1>.var count=$("#cusChildTypeId").get(0).options.length;
     for(var i=0;i<count;i++)  
         {           
  if($("#cusChildTypeId").get(0).options.text == text)  
         {  
             $("#cusChildTypeId").get(0).options.selected = true;
             break;  
         }  
        }
 2>.$("#cusChildTypeId").val(text);
    $("#cusChildTypeId").change();

抱歉!评论已关闭.