DIV CSS 佈局教程網

jQuery 操作 checkbox 總整理:全選、取消、奇偶選、反選與取值
編輯:JQuery入門技巧     

checkbox 的操作看起來簡單,實際寫起來卻散落在 attr、removeAttr、prop、各種選擇器之間。本文把常用的七種操作整理成可直接複製的片段,最後附一個完整可跑的頁面。

一、全選

$("#btn1").click(function () {
    $("input[name='checkbox']").attr("checked", "true");
});

二、取消全選

$("#btn2").click(function () {
    $("input[name='checkbox']").removeAttr("checked");
});

三、選中所有奇數項

$("#btn3").click(function () {
    $("input[name='checkbox']:odd").attr("checked", "true");
});

四、選中所有偶數項

$("#btn6").click(function () {
    $("input[name='checkbox']:even").attr("checked", "true");
});

要注意 jQuery 的 :odd / :even 是以 0 為起點的,所以 :even 選到的是畫面上第 1、3、5 個,跟一般人的「偶數」語感相反。實務上如果需要符合直覺,用 eq() 搭配索引判斷反而比較不容易搞混。

五、反選

$("#btn4").click(function () {
    $("input[name='checkbox']").each(function () {
        if ($(this).attr("checked")) {
            $(this).removeAttr("checked");
        } else {
            $(this).attr("checked", "true");
        }
    });
});

或者寫得更短:

$("#invert").click(function () {
    $("#ruleMessage [name='delModuleID']:checkbox").each(function (i, o) {
        $(o).attr("checked", !$(o).attr("checked"));
    });
});

六、取得所有選中項的值

var aa = "";
$("#btn5").click(function () {
    $("input[name='checkbox']:checkbox:checked").each(function () {
        aa += $(this).val();
    });
    document.write(aa);
});

用 map() 會更乾淨,直接拿到陣列:

var values = $("input[name='checkbox']:checked").map(function () {
    return this.value;
}).get();

七、遍歷選中項

$("input[type=checkbox][checked]").each(function () {
    // 核選框通常會有多個,逐一處理
    alert($(this).val());
});

完整可執行範例

<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>checkbox 操作示範</title>
<script src="js/jquery-1.6.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function ($) {

    // 全選
    $("#btn1").click(function () {
        $("input[name='checkbox']").attr("checked", "true");
    });

    // 取消全選
    $("#btn2").click(function () {
        $("input[name='checkbox']").removeAttr("checked");
    });

    // 選中所有偶數索引(第一、三、五…)
    $("#btn3").click(function () {
        $("input[name='checkbox']:even").attr("checked", "true");
    });

    // 選中所有奇數索引(第二、四、六…)
    $("#btn6").click(function () {
        $("input[name='checkbox']:odd").attr("checked", "true");
    });

    // 反選
    $("#btn4").click(function () {
        $("input[name='checkbox']").each(function () {
            $(this).prop("checked", !$(this).prop("checked"));
        });
    });

    // 取得選中的所有值
    $("#btn5").click(function () {
        var aa = "";
        $("input[name='checkbox']:checkbox:checked").each(function () {
            aa += $(this).val();
        });
        alert(aa);
    });
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
  <input type="button" id="btn1" value="全選">
  <input type="button" id="btn2" value="取消全選">
  <input type="button" id="btn3" value="選中所有奇數">
  <input type="button" id="btn6" value="選中所有偶數">
  <input type="button" id="btn4" value="反選">
  <input type="button" id="btn5" value="獲得選中的所有值">
  <br>
  <input type="checkbox" name="checkbox" value="checkbox1"> checkbox1
  <input type="checkbox" name="checkbox" value="checkbox2"> checkbox2
  <input type="checkbox" name="checkbox" value="checkbox3"> checkbox3
  <input type="checkbox" name="checkbox" value="checkbox4"> checkbox4
  <input type="checkbox" name="checkbox" value="checkbox5"> checkbox5
  <input type="checkbox" name="checkbox" value="checkbox6"> checkbox6
  <input type="checkbox" name="checkbox" value="checkbox7"> checkbox7
  <input type="checkbox" name="checkbox" value="checkbox8"> checkbox8
</div>
</form>
</body>
</html>

最重要的一件事:請改用 prop()

上面那些 attr("checked", "true") 的寫法,在 jQuery 1.6 之後其實是有問題的。原因在于 checked、selected、disabled 這些是元素的狀態屬性(property),而不是 HTML 上的初始屬性(attribute)。

attr("checked") 讀到的是「這個元素當初寫 HTML 時有沒有 checked」,永遠不會改變;prop("checked") 讀到的才是「它現在有沒有被勾選」。用錯會導致反選失效、全選狀態判斷錯誤這類難以察覺的 bug。

正確的對照如下:

// 全選
$("input[name='checkbox']").prop("checked", true);

// 取消全選
$("input[name='checkbox']").prop("checked", false);

// 反選
$("input[name='checkbox']").each(function () {
    this.checked = !this.checked;
});

// 判斷是否全選(用 filter 比數長度最可靠)
var $all = $("input[name='checkbox']");
var $on  = $all.filter(":checked");
$("#selectAll").prop("checked", $all.length === $on.length && $all.length > 0);

如果專案還在用 jQuery 1.6 之前的舊版本,才需要回到 attr 的寫法。新專案請一律統一用 prop(),能省下大量「為什麼反選沒作用」的除錯時間。

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