Enterキーでfocus移動 (.focusable 限定版)
HTML
<h1>Enterキーでfocus移動 (.focusable 限定ver</h1>
<h2>getElementsByClassName() ver</h2>
<form id="sample1" action="test.php">
<input class="focusable" type="text" name="a" /><br>
<input type="checkbox" name="c1" /><br>
<input class="focusable" type="text" name="b" /><br>
<input type="checkbox" name="c2" /><br>
<input class="focusable" type="text" name="c" disabled /><br>
<input class="focusable" type="text" name="d" /><br>
<input class="focusable" type="text" name="e" /><br>
</form>
<h2>querySelectorAll() ver</h2>
<form id="sample2" action="test.php">
<input class="focusable" type="text" name="a" /><br>
<input type="checkbox" name="c1" /><br>
<input class="focusable" type="text" name="b" /><br>
<input type="checkbox" name="c2" /><br>
<input class="focusable" type="text" name="c" disabled /><br>
<input class="focusable" type="text" name="d" /><br>
<input class="focusable" type="text" name="e" /><br>
</form>
<ul>
<li><a href="https://teratail.com/questions/325107">JavaScript - Js特定の要素にフォーカス移動する|teratail</a></li>
</ul>
JavaScript
document.getElementById('sample1').addEventListener('keydown', function handleKeydown (event) {
const input = event.target;
if (event.code !== 'Enter' || input.tagName !== 'INPUT' || input.type !== 'text') return;
const targets = document.getElementsByClassName('focusable');
let i = Array.prototype.indexOf.call(targets, input), nextInput;
while (nextInput = targets[++i], nextInput && nextInput.disabled);
if (nextInput) nextInput.focus();
}, false);
document.getElementById('sample2').addEventListener('keydown', function handleKeydown (event) {
const input = event.target;
if (event.code !== 'Enter' || input.tagName !== 'INPUT' || input.type !== 'text') return;
const nextInput = input.form.querySelector('.focusable:focus~.focusable:enabled');
if (nextInput) nextInput.focus();
}, false);