DIV CSS 佈局教程網

jQuery 遍歷核取方塊,把勾選項的 value 收攏起來
編輯:JavaScript綜合知識     

批次操作時常需要把勾選的項目收集成一個字串,再塞進隱藏欄位一起送出。以下是完整寫法。

源碼

jQuery(function ($) {
    $("input[name='key']:checkbox").click(function () {
        var ids = '';
        var flag = 0;
        $("#ids").attr("value", ids);

        $("input[name='key']:checkbox").each(function () {
            if (true == $(this).attr("checked")) {
                ids += $(this).attr('value') + ',';
                flag += 1;
            }
        });

        if (0 < flag) {
            $("#ids").attr("value", ids);
            return true;
        } else {
            alert('請至少選擇一項!');
            return false;
        }
    });
});

功能說明

取得 name='key' 的複選框值,將選中項的 value 以逗號串接,寫到隱藏域中:

<input type="hidden" name="ids" id="ids" value="" />

核心語句

$("input[name='key']:checkbox").each(function () {
    if (true == $(this).attr("checked")) {
        ids += $(this).attr('value') + ',';
    }
});

一個容易踩的坑

在 HTML 中,如果一個複選框被選中,對應的標記為 checked="checked"。但如果用 jQuery 讀 $("#id").attr("checked"),則會提示您是 "true" 而不是 "checked",所以判斷 if("checked" == $("#id").attr("checked")) 是錯誤的,應該如上面那樣書寫:

if (true == $("#id").attr("checked")) { ... }

更根本的解法是改用專門表示狀態的 API:$(this).prop("checked") 或直接用原生屬性 this.checked。attr 反映的是 HTML 初始標記,prop 反映的是目前狀態,兩者混用正是這類 bug 的來源。

另外,串接完記得去掉最後多餘的逗號(ids.slice(0, -1));用 map + join 會更乾淨:

var ids = $("input[name='key']:checked").map(function () {
    return this.value;
}).get().join(',');
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved