方法:

("元素").each(function() {...});

.prop為判斷元素

程式範例:

.prop為判斷元素是否為true或false,方法如下:

("#boxAll").prop("checked")


("#boxAll").prop("checked",true)改成true的方法。
("#boxAll").prop("checked",false)改成false的方法。


name名稱找到開頭字串「checkbox」後執行函數,方法如下:

("input[name='checkbox']").each(function() {
(this).prop("checked", true);
//上句等於("input[name='checkbox']").prop("checked", true);
 
});

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>核取方塊全選的方法</title>
</head>
<script src="https://code.jquery.com/jquery-3.4.1.slim.js"></script>
<script language="javascript">
    (document).ready(function(){
    ("#boxAll").click(function() {
   if(("#boxAll").prop("checked")) {
     ("input[name='checkbox']").each(function() {
         (this).prop("checked", true);
     });
   } else {
     ("input[name='checkbox']").each(function() {
         (this).prop("checked", false);
     });           
   }
});
    });
</script>

<body>
<form id="form1" name="form1" method="post">
  <p>
    <input type="checkbox" name="checkbox_1" value="藍色"/>
    <label for="checkbox_1">藍色</label>
        <input type="checkbox" name="checkbox_2" value="紅色"/>
    <label for="checkbox_2">紅色</label>
        <input type="checkbox" name="checkbox_3" value="黃色"/>
    <label for="checkbox_3">黃色</label>
        <input type="checkbox" name="checkbox_4" value="紫色"/>
    <label for="checkbox_4">紫色</label>

    <input type="checkbox" name="boxAll" id="boxAll">
    <label for="boxAll">全選</label>

</form>
</body>
</html>

文章標籤
全站熱搜
創作者介紹
創作者 小甲學習地 的頭像
小甲學習地

學習資訊部落

小甲學習地 發表在 痞客邦 留言(0) 人氣(238)