Jquery checkbox(全选/不全选、反选、单选、获取选中的值)

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全选练习</title>
    <script src="js/jquery-3.4.1.js"></script>
</head>
<body>
<form action="http://www.baidu.com" method="post">
    <p>你喜欢的食物?</p>
    <input type="checkbox" name="foods"  value="麦当劳" />麦当劳
    <input type="checkbox" name="foods"  value="肯德基" />肯德基
    <input type="checkbox" name="foods"  value="汉堡王" />汉堡王
    <input type="checkbox" name="foods"  value="必胜客" />必胜客

    <p>
        <input type="checkbox" id="checkAll" />全选/全不选
        <input type="button"   id="reverse" value="反选" />
        <input type="button"   id="submit"  value="提交" />
    </p>
</form>
</body>
</html>
<script>
    $(function () {
        const checkAll = $('#checkAll');   // 全选/不全选
        const checkboxALL = $(':checkbox[name = foods]'); // 所有元素checkbox
        const reverse = $('#reverse'); // 反选
        const submit = $('#submit'); // 提交

        // 全选与取消全选
        checkAll.click(function () {
            checkboxALL.prop('checked', this.checked);
        });

        // 反选
        reverse.click(function () {
            $.each(checkboxALL, function() {
                this.checked = !this.checked;
            });

            checkAll.prop('checked', checkboxALL.filter(':not(:checked)').length === 0); // 是否全选
        });

        // 单个点击
        checkboxALL.click(function () {
            console.log(this.value); // 获取点击checkbox的属性
            checkAll.prop('checked', checkboxALL.filter(':not(:checked)').length === 0); // 是否全选
        });

        // 提交
        submit.click(function () {
            let checkboxValue = []; // 所有选中的checkbox的值

            checkboxALL.filter(':checked').each(function () {
                checkboxValue.push(this.value);
            });
        })

    })
</script>

判断某个checkbox是否选中,返回值: Boolean
$("#XXX").eq(index).is(':checked')
$("#XXX")[index].checked

设置某个checkbox的选中与不选中
$("#XXX").eq(index).prop('checked', true/false)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值