複数のチェックボックスのcheckedを一気に更新するHTML & Javascriptのサンプル.

チェックボックスのidやnameがばらばらでも大丈夫な例.

<script type="text/javascript">
<!--
    function checkAll(checkbox, targetIds) {
        var checked = checkbox.checked;
        for (i = 0; i < targetIds.length; i++) {
			var target = document.getElementById(targetIds[i]);
	        target.checked = checked;
        }
    }
//-->
</script>

<input type="checkbox" id="allCheck" onclick='checkAll(this, new Array("foo", "bar", "baz"));' />
<label for="allCheck">すべて選択</label>
<br />

<input type="checkbox" id="foo" name="foo" value="foo" /><label for="foo">foo</label><br />
<input type="checkbox" id="bar" name="bar" value="bar" /><label for="bar">bar</label><br />
<input type="checkbox" id="baz" name="baz" value="baz" /><label for="baz">baz</label><br />

チェックボックスがたくさんあって上記のやり方では面倒な場合は,複数のチェックボックスをdivでくるんでおいてその子供を一気にcheckedを更新するのもありかも.以下はその例.

<script type="text/javascript">
<!--
    function checkAll(checkbox, targetId) {
        var checked = checkbox.checked;
        var children = document.getElementById(targetId).childNodes;
        for (i = 0; i < children.length; i++) {
			if (children[i].type == "checkbox") {
	            children[i].checked = checked;
			}
        }
    }
//-->
</script>

<input type="checkbox" id="allCheck" onclick='checkAll(this, "checkboxes");' />
<label for="allCheck">すべて選択</label>
<br />

<div id="checkboxes">
	<input type="checkbox" id="foo" name="foo" value="foo" /><label for="foo">foo</label><br />
	<input type="checkbox" id="bar" name="bar" value="bar" /><label for="bar">bar</label><br />
	<input type="checkbox" id="baz" name="baz" value="baz" /><label for="baz">baz</label><br />
</div>


コメントを書く




XHTML: 次のタグが使用できます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: 投稿されたコメントが表示されるにはいくらかの時間がかかります.投稿後直ちに表示されませんが投稿ボタンを何度も押さないようお願いします.