1
1

More than 1 year has passed since last update.

全てのチェックボックスにチェックが入る全選択ボタンを実装する

Posted at

はじめに

業務で実装した内容の忘備録として残しております。
これが正解!というものではないので、参考程度にご覧ください。
また、間違っているところ等あればご指摘頂けると幸いです。

仕様

HTMLとJQueryを使って「全選択」ボタンを押下することで複数のチェックボックスに一括チェックする。また、再度「全選択」ボタンを押下すると全てのチェックが外れる。

実装イメージ

◉全選択ボタン押下後
スクリーンショット 2022-10-20 0.27.41.png
◉再度全選択ボタンを押下
スクリーンショット 2022-10-20 0.29.08.png

環境

  • エディター:CodeSandbox
  • HTML:1.0.0
  • JQuery:3.6.1

HTML

◉全選択ボタンの実装

<input type="button" id="select-all" value="全選択">

◉テーブル内のチェックボックスの実装
ポイントは一括でチェックを入れるためにname属性をつけること!

<td>
	<input type="checkbox" name="check">
</td>

◉テーブル部分のコード全体

<table border="1" style="width: 50%; font-size: 100%; border-collapse: collapse">
		<thead style="background-color: #BDBDB7;">
			<tr align="center">
				<th>更新ステータス<br><input type="button" id="select-all" value="全選択"></th>
				<th>施設名</th>
				<th>場所</th>
				<th>料金</th>
			</tr>
			<tbody>
				<tr align="center">
					<td>
						<input type="checkbox" name="check">
					</td>
					<td>らかんの湯</td>
					<td>佐賀県</td>
					<td>日帰り4,500円</td>
				</tr>
				<tr align="center">
					<td>
						<input type="checkbox" name="check">
					</td>
					<td>ホテルマウント富士</td>
					<td>山梨県</td>
					<td>日帰り2,200円</td>
				</tr>
				<tr align="center">
					<td>
						<input type="checkbox" name="check">
					</td>
					<td>サウナしきじ</td>
					<td>静岡県</td>
					<td>男性:1,400円/女性:900円</td>
				</tr>
			</tbody>	
		</thead>	
	</table>

JavaScript(jQuery)

チェックボックスやラジオボタンの値を取得できるpropメソッドを使用。
クリックされた回数が2で割り切ることができなければ一括チェック、割り切れた場合はチェックを外す処理を追加。

import $ from "jquery";
let clickCount = 0;
$(function () {
  $("#select-all").click(function () {
    clickCount += 1;
    if (clickCount % 2 === 1) {
      $("input[name=check]").prop("checked", true);
    } else {
      $("input[name=check]").prop("checked", false);
    }
  });
});
1
1
3

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
1
1