DIV CSS 佈局教程網

jQuery 操作 select 與 option 的完整用法整理
編輯:JavaScript綜合知識     

下拉選單的讀取、設定、增刪,是表單處理中最常被翻API的幾件事。以下把 jQuery 操作 select 的常用寫法系統性整理,並附上連動分類與全選的實例。

取得 select 的目前選項

$("#select_id").change(function() {
    // 為 Select 添加事件,選擇其中一項時觸發
});

var checkText  = $("#select_id").find("option:selected").text();  // 選中項的文字
var checkValue = $("#select_id").val();                           // 選中項的值
var checkIndex = $("#select_id").get(0).selectedIndex;            // 選中項的索引
var maxIndex   = $("#select_id option:last").attr("index");       // 最大索引值

設定 select 的選中項

$("#select_id").get(0).selectedIndex = 1;   // 依索引選中
$("#select_id").val(4);                     // 依 value 選中
$("#select_id option[text='jQuery']").attr("selected", true);   // 依文字選中

新增與刪除 option

$("#select_id").append("<option value='Value'>Text</option>");  // 追加一項
$("#select_id").prepend("<option value='0'>請選擇</option>");     // 插入到最前面
$("#select_id option:last").remove();                             // 刪除最後一項
$("#select_id option[index='0']").remove();                       // 刪除索引 0
$("#select_id option[value='3']").remove();                       // 刪除 value 為 3
$("#select_id option[text='4']").remove();                        // 刪除文字為 4

實例:連動分類的重置

三級、四級分類連動時,需要在上層變動後清空下層,但保留那個「請選擇」的預設項:

<select name="thirdLevel" id="thirdLevel" onchange="getFourthLevel()">
    <option value="0" id="thirdOption">請選擇三級分類</option>
</select>

<select name="fourthLevelId" id="fourthLevelId">
    <option value="0" id="fourthOption">請選擇四級分類</option>
</select>

<script>
if ($("#thirdLevel").val() != 0) {
    $("#thirdLevel option[value!=0]").remove();
}
if ($("#fourthLevelId").val() != 0) {
    $("#fourthLevelId option[value!=0]").remove();
}
</script>

邏輯是:若下層已有資料則刪除,若無資料則維持預設值。搭配 Ajax 之後,這就是動態載入子分類的標準起手式。

另一組常用寫法

// 取得
$("#ddlRegType").find("option:selected").text();   // 選中的文字
$("#ddlRegType").val();                            // 選中的值
$("#ddlRegType").get(0).selectedIndex;             // 選中的索引

// 設定
$("#ddlRegType").get(0).selectedIndex = index;     // 依索引
$("#ddlRegType").val("Normal");                    // 依 value
$("#ddlRegType").get(0).value = value;             // 直接改 value

// 依文字設定,需迴圈比對
var count = $("#ddlRegType option").length;
for (var i = 0; i < count; i++) {
    if ($("#ddlRegType").get(0).options[i].text == text) {
        $("#ddlRegType").get(0).options[i].selected = true;
        break;
    }
}

// 清空整個 select
$("#ddlRegType").empty();

附錄:checkbox 全選與反選

$("document").ready(function() {
    $("#btn1").click(function() {
        $("[name='checkbox']").attr("checked", 'true');   // 全選
    });
    $("#btn2").click(function() {
        $("[name='checkbox']").removeAttr("checked");     // 取消全選
    });
    $("#btn3").click(function() {
        $("[name='checkbox']:even").attr("checked", 'true');  // 選中奇數項
    });
    $("#btn4").click(function() {
        $("[name='checkbox']").each(function() {          // 反選
            if ($(this).attr("checked")) {
                $(this).removeAttr("checked");
            } else {
                $(this).attr("checked", 'true');
            }
        });
    });
    $("#btn5").click(function() {                         // 輸出選中的值
        var str = "";
        $("[name='checkbox'][checked]").each(function() {
            str += $(this).val() + "\n";
        });
        alert(str);
    });
});

版本提醒

範例中的 option[text='jQuery'] 與 attr("selected", true) 都是舊寫法。依文字選擇較穩妥的方式是先用 filter 比對:

$("#select_id option").filter(function() {
    return $(this).text() === 'jQuery';
}).prop("selected", true);

另外,selected、checked 這類狀態在 jQuery 1.6 之後應改用 prop();option 的 index 屬性並非標準,範例中 option:last 已足以取得最後一項,不必依賴它。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved