1
1

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備忘録:あまりないcontenteditableな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 contenteditable=true>80</td>
				<td contenteditable=true>120</td>
			</tr>
			<tr>
				<td><input type="checkbox"></td>
				<td>2</td>
				<td>みかん</td>
				<td contenteditable=true>45</td>
				<td contenteditable=true>88</td>
			</tr>
			<tr>
				<td><input type="checkbox"></td>
				<td>3</td>
				<td>いちじく</td>
				<td contenteditable=true>105</td>
				<td contenteditable=true>311</td>
			</tr>
			<tr>
				<td><input type="checkbox"></td>
				<td>4</td>
				<td>ぶどう</td>
				<td contenteditable=true>72</td>
				<td contenteditable=true>112</td>
			</tr>
		</tbody>
	</table>
</body>
</html>

単価と在庫を編集できる的な感じにしておく

書いたことに自信が無いので間違っている可能性大なメモ

Enterキーでフォーカス移動したい

script.js
(function($) {
	$.fn.focusHelper = function() {
		$(document).on('keydown', this.selector + ' td[contenteditable=true]', function(event) {
			if (window.event) {
				keyCode = window.event.keyCode;
				shiftKey = window.event.shiftKey;
			} else {
				keyCode = ev.which;
				shiftKey = ev.shiftKey;
			}
			if (keyCode == 13 || keyCode == 9) {
				event.preventDefault();
				if (!shiftKey) {
					if (!$(this).next().is('td[contenteditable=true]')) {
						$(this).parent().next().children('td[contenteditable=true]:first').focus();
					} else {
						$(this).next().focus();
					}
				} else {
					if (!$(this).prev().is('td[contenteditable=true]')) {
						$(this).parent().prev().children('td[contenteditable=true]:last').focus();
					} else {
						$(this).prev().focus();
					}
				}
			}
		});
	};
})( jQuery );

とりあえず、TABキーも同様な動きにしてみる。

なぜならば、TABキーでフォーカス移動するとチェックボックスにフォーカス移動しちゃうからw

$('#hoge-body').focusHelper();

でいけると思う。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?