如何用jQuery獲得select的值

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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章