jQuery操作選中select下拉框的值


js和jQuery聯合操作dom真的很好用,如果不是專業前端人員的話,我覺得吧前端語言只要熟練掌握js和jQuery就可以了。
獲取select下拉框的幾種情況如下:

1.獲取第一個option的值

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

2.最后一個option的值

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

3.獲取第二個option的值

$('#test option:eq(1)').val();
依次類推可以獲取第三個、第四個option的值

4.獲取選中的值

var groupid = $("#groupid").find("option:checked").val();
$('#groupidoption:selected').val();
$('#groupid').val();
<td align="center" class="tableFormLabel" >
    <select id="groupid" class="input-text" >  </select>
</td>

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

var str="<option value='n+1'>第N+1項</option>";
$("#test").append(str); //一般都用這個追加

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

9.刪除選中項

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

10.刪除項選中的第一項

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

11.刪除滿足條件的option

$('#test option').each(function(){
   if( $(this).val() == '5'){
        $(this).remove();
    }
});

$('#test option[value=5]').remove();

參考博客:https://www.cnblogs.com/eager/p/7133270.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM