Skip to content

Note

不挑戰記憶力的技術筆記

Menu
Menu

[JQuery]對 select 的操作方式

Posted on 2012 年 10 月 3 日 by febr
1. 取得option的值

//  get選取option的文字
$('#select').find(':selected').text();
//  get選取option的值
$('#select').find(':selected').val();

//  用迴圈取得所有被選取的option
$('#select').find(':selected').each(function() {
    alert(this.text);    //  文字
    alert(this.value);   //  值
});

2. 新增option

$('#select').append( $('').attr('value', "值").text('文字') );

3. 刪除option

//  移除選擇的option
$('#select').find(':selected').remove();

//  移除全部的option
$('#select option').remove();

4. 移除選擇的option後,防止卷軸移至最上方

//  先取得要移除項目的 index
var selectIndex = $('#select').find(':selected').index();

//  移除選擇的項目
$('#select').find(':selected').remove();

//  判斷移除項目後,原先的index是否還有option,有的話就直接將此option設定為選取狀態
//  捲軸就不會往上跑了
if ($('#select option').get(selectIndex) != null) {
    $('#select option').get(selectIndex).selected = true;
}
else {
    //  沒有項目的話,判斷select理是否還有option
    //  有的話,表示移除的項目為最後一個,就設定上一個option為選取狀態
    if ($('#select option').length > 0) {
        $('#select option').get(selectIndex - 1).selected = true;
    }
}

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

近期文章

  • [AWS] S3 Object Initiate restore (復原回 Standard)
  • [Windows] 使用者快速登出的方法 Logout/ Logoff/Sign Out from Windows User Account
  • [Windows] Windows 11 安裝Server管理工具Install RSAT(Remote Server Administrator Tools)
  • Chrome出現:你的連線不是私人連線 Your connection is not private
  • [C#] 取得 Request URL 的方法

近期留言

    彙整

    分類

    • Ajax
    • Android
    • ASP
    • ASP.NET MVC
    • Azure
    • C#
    • Cisco
    • CSS
    • Delphi
    • Developer Tools
    • Framework
    • FreeBSD
    • Git
    • HTML5
    • javascript
    • jQuery
    • Juniper
    • Linux
    • Mac
    • PHP
    • Python
    • Server&OS
    • Software
    • SQL server
    • Sublime Text
    • Ubuntu
    • Visual Studio
    • Vmware
    • Web Design
    • Web Development
    • Windows
    • WordPress
    • 未分類
    • 未分類

    彙整

    分類

    • Ajax
    • Android
    • ASP
    • ASP.NET MVC
    • Azure
    • C#
    • Cisco
    • CSS
    • Delphi
    • Developer Tools
    • Framework
    • FreeBSD
    • Git
    • HTML5
    • javascript
    • jQuery
    • Juniper
    • Linux
    • Mac
    • PHP
    • Python
    • Server&OS
    • Software
    • SQL server
    • Sublime Text
    • Ubuntu
    • Visual Studio
    • Vmware
    • Web Design
    • Web Development
    • Windows
    • WordPress
    • 未分類
    • 未分類

    其他操作

    • 登入
    • 訂閱網站內容的資訊提供
    • 訂閱留言的資訊提供
    • WordPress.org 台灣繁體中文
    © 2025 Note | Powered by Superbs Personal Blog theme