Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

jQueryで全てのチェックボックスの全選択、全解除を行う(ショートカットキー付き) おまけでZen-Codingレシピつき

概要

jQueryで全てのチェックボックスの全選択、全解除を行う。
また、全選択・全解除ボタンにショートカットキーを割り当てる。

書式

Selectors API使用
elements指定とattributeのフィルタを併用する

  $("input[type='checkbox']").attr('checked', boolean);

ショートカットキーについて

ショートカットの指定をするボタンに
accesskey="任意のキー"
を設定することが可能。

accesskey="N"

であれば、Alt+Shift+Nでキーアクセスが可能。
ChromeFireFoxの場合はAlt+Shift+任意のキー。
IEの場合はAlt+任意のキー。

サンプルコード

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<script type="text/javascript" src="../JQuery/jquery.js"></script>
<script type="text/javascript">

function doCheckOnAll() {
  setCheckAll(true);
}
function doCheckOffAll() {
  setCheckAll(false);
}

function setCheckAll(checked) {
  $("input[type='checkbox']").attr('checked', checked);
}
</script>
</head>
<body>
<form action="" name="form1">
<div id="parent">
	<input type="checkbox" name="chk" id="checkTest1" value="1">
	<input type="checkbox" name="chk" id="checkTest2" value="2">
	<input type="checkbox" name="chk" id="checkTest3" value="3">
	<input type="checkbox" name="chk" id="checkTest4" value="4">
	<input type="checkbox" name="chk" id="checkTest5" value="5">
</div>
<input type="button" name="checkOnAll" value="全選択(N)" onClick="doCheckOnAll()" accesskey="N">
<input type="button" name="checkOffAll" value="全解除(F)" onClick="doCheckOffAll()" accesskey="F">
<hr>
<pre>
Chrome:Alt+Shift+N or Fでキー操作可能
FireFox:Alt+Shift+N or Fでキー操作可能
IE:Alt+N or Fでキー操作可能
</pre>

<hr>
</form>
</body>
</html>

サンプル画像


おまけのZen-Codingレシピ

展開前
html>(head+(meta:utf)+(script[src=../JQuery/jquery.js])+script+style)+body>form[action="" name="form1"]>(div#parent>input[type="checkbox" name="chk" id="checkTest$"]*5+input[type="button"]*2+hr+pre+hr)
展開後
<html>
    <head></head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <script type="text/javascript" src="../JQuery/jquery.js"></script>
    <script type="text/javascript"></script>
    <style type="text/css"></style>
    <body>
        <form action="" name="form1">
            <div id="parent"><input type="checkbox" name="chk" value="" id="checkTest1"><input type="checkbox" name="chk" value="" id="checkTest2"><input type="checkbox" name="chk" value="" id="checkTest3"><input type="checkbox" name="chk" value="" id="checkTest4"><input type="checkbox" name="chk" value="" id="checkTest5"><input type="button" name="" value=""><input type="button" name="" value="">
                <hr>
                <pre></pre>
                <hr>
            </div>
        </form>
    </body>
</html>