欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用js实现多选框

程序员文章站 2022-07-13 23:04:45
...
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多选框</title>
    <style>
        * {
            margin: 0px;
            padding: 0px;
        }

        ul {
            list-style: none;
            display: flex;
        }
    </style>
</head>

<body>
    <form action="">
        <ul>
            <li>
                西瓜<input type="checkbox">
            </li>
            <li>
                苹果<input type="checkbox">
            </li>
            <li>
                葡萄<input type="checkbox">
            </li>
            <li>
                榴莲<input type="checkbox">
            </li>
        </ul>
        <input type="button" value="全选" id="all_btn">
        <input type="button" value="全不选" id="notall_btn">
        <input type="button" value="反选" id="invert">
    </form>
    <script>
        let all_btn = document.getElementById("all_btn");
        let notall_btn = document.getElementById("notall_btn");
        let invert = document.getElementById("invert");
        let check = document.querySelectorAll(`input[type="checkbox"]`);
        all_btn.onclick = function () {
            check.forEach((item) => {
                item.checked = true;
            })
        };
        notall_btn.onclick = function () {
            check.forEach((item) => {
                item.checked = false;
            })
        };
        invert.onclick = function () {
            check.forEach((item) => {
                // item.checked ? item.checked = true : item.checked = false;
                item.checked=!item.checked;
            })
        };
    </script>
</body>

</html>
相关标签: javascript