0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

全てのチェックボックスをチェック、または解除するjs

Posted at
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>チェックボックス一括切り替えサンプル</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; padding: 20px; }
        form { border: 1px solid #ddd; padding: 20px; margin-bottom: 20px; }
        button { margin-bottom: 10px; }
    </style>
</head>
<body>
    <h1>チェックボックス一括切り替えサンプル</h1>
    
    <form>
        <button type="button" class="js-toggleAllCheckboxes">全てのチェックボックスを切り替え</button>
        <br>
        <input type="checkbox" id="item1" name="item1">
        <label for="item1">アイテム1</label><br>
        <input type="checkbox" id="item2" name="item2">
        <label for="item2">アイテム2</label><br>
        <input type="checkbox" id="item3" name="item3">
        <label for="item3">アイテム3</label><br>
        <input type="checkbox" id="item4" name="item4">
        <label for="item4">アイテム4</label><br>
    </form>

    <script>
    function toggleAllCheckboxes(element) {
        const form = element.closest('form');
        if (!form) return;

        const checkboxes = form.querySelectorAll('input[type="checkbox"]');
        const allChecked = Array.from(checkboxes).every(checkbox => checkbox.checked);

        checkboxes.forEach(checkbox => {
            checkbox.checked = !allChecked;
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        const toggleButtons = document.querySelectorAll('.js-toggleAllCheckboxes');

        toggleButtons.forEach(button => {
            button.addEventListener('click', function() {
                toggleAllCheckboxes(this);
            });
        });
    });
    </script>
</body>
</html>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?