5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JQuery備忘録:ありがちなtableとチェックボックスのやつ

Posted at

table関係のJQueryライブラリだとかプラグインとかあるけれども、
どうもデザインが引っ張られてアレになってしまうので、ちょっと書いてみた。

index.html
<html>
<body>
	<table>
		<thead id="hoge-head">
			<tr>
				<th><input type="checkbox"></th>
				<th>No</th>
				<th>商品</th>
				<th>単価</th>
				<th>在庫</th>
			</tr>
		</thead>
		<tbody id="hoge-body">
			<tr>
				<td><input type="checkbox"></td>
				<td>1</td>
				<td>りんご</td>
				<td>80</td>
				<td>120</td>
			</tr>
			<tr>
				<td><input type="checkbox"></td>
				<td>2</td>
				<td>みかん</td>
				<td>45</td>
				<td>88</td>
			</tr>
			<tr>
				<td><input type="checkbox"></td>
				<td>3</td>
				<td>いちじく</td>
				<td>105</td>
				<td>311</td>
			</tr>
			<tr>
				<td><input type="checkbox"></td>
				<td>4</td>
				<td>ぶどう</td>
				<td>72</td>
				<td>112</td>
			</tr>
		</tbody>
	</table>
</body>
</html>

書いたことないので間違っている可能性大なメモ

theadにあるチェックボックスで全選択&解除がしたい

script.js
(function($) {
	$.fn.checkboxSelectAll = function() {
		$(document).on('click', this.selector + ' th input[type="checkbox"]', function(event) {
			var table = $(event.target).parents('table');
			$('td input[type="checkbox"]', table).attr('checked', event.target.checked);
		});
	};
})( jQuery );

$('#hoge-head').checkboxSelectAll();

と書いておけばイケる。

tbodyにあるチェックしてる行が知りたい

script.js
(function($) {
	$.fn.checkboxSelection = function() {
		result = new Array();
		$(this.selector + ' tr').each(function (index, row) {
	        if ($(row).find('input:checkbox').is(':checked')){
	        	result.push(index);
			}
	    });
		return result;
	};
})( jQuery );

$('#hoge-body').checkboxSelection()

で選択行番号(0〜)が配列で帰ってくる

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?