<!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>
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme