Steven5007

导航

如何用jQuery获得select的值

https://www.cnblogs.com/eager/p/7133270.html

1.获取第一个option的值       

 $('#test option:first').val();

 

2.最后一个option的值                     

$('#test option:last').val();

 

3.获取第二个option的值          

$('#test option:eq(1)').val();

 

4.获取选中的值                         

$('#test').val();

$('#test option:selected').val();

 

5.设置值为2的option为选中状态   

$('#test').attr('value','2');

 

6.设置最后一个option为选中

$('#test option:last').attr('selected','selected');

$("#test").attr('value' , $('#test option:last').val());

$("#test").attr('value' , $('#test option').eq($('#test option').length - 1).val());

 

7.获取select的长度            

$('#test option').length;

 

8.添加一个option

$("#test").append("<option value='n+1'>第N+1项</option>");

$("<option value='n+1'>第N+1项</option>").appendTo("#test");

 

9.添除选中项       

 $('#test option:selected').remove();

 

10.删除项选中(这里删除第一项)       

$('#test option:first').remove();

 

11.指定值被删除

复制代码
$('#test option').each(function(){

   if( $(this).val() == '5'){

        $(this).remove();
    }
});

$('#test option[value=5]').remove();
复制代码

 

12.获取第一个Group的标签

$('#test optgroup:eq(0)').attr('label');

 

13.获取第二group下面第一个option的值

$('#test optgroup:eq(1) : option:eq(0)').val();

 

14.根据option的值选中option

$("#sel option:contains('C')").prop("selected", true);

 

15. 获取option的value值 、文本值

<select id="id"> 
  <option value="A" url="http://www.baidu.com">第一个文本值</option>
  <option value="B" url="http://www.qq.com">第二个文本值</option>
</select>
JavaScript原生的方法:
1:拿到select对象: `var myselect=document.getElementById("select"); 
2:拿到选中项的索引:var index=myselect.selectedIndex ; // selectedIndex代表的是你所选中项的index
3:拿到选中项options的value: myselect.options[index].value;
4:拿到选中项options的text: myselect.options[index].text;
5:拿到选中项的其他值,比如这里的url: myselect.options[index].getAttribute('url');
jQuery方法:
1:var options=$(“#id option:selected”); //获取选中的项 
2:alert(options.val()); //拿到选中项的值
3:alert(options.text()); //拿到选中项的文本
4:alert(options.attr('url')); //拿到选中项的url值
或者
var param= $("#id").find("option:selected").val(); //A 获取value值

var param= $("#id").find("option:selected").text(); //第一个文本值 获取文本值
 

 

posted on 2018-09-26 19:02  Steven5007  阅读(970)  评论(0编辑  收藏  举报