Ⅰ.はじめに
<input id="text1" type="text">
にフォーカスがある状態でEnterキー
を押すと、<input id="text2" type="text">
にフォーカスを移動させるプログラムを書いています。
<input id="text2" type="text">
の次は<input id="text3" type="text">
です。
<input id="text3" type="text">
の次は<input id="text1" type="text">
に戻ります。
https://jsfiddle.net/66vs2wu5/
HTML
1<input id="text1" type="text" placeholder="1"> 2<input id="text2" type="text" placeholder="2"> 3<input id="text3" type="text" placeholder="3">
js
1$('#text1').on('keyup', function (e) { 2 if (e.keyCode == 13) { 3 $('#text2').focus(); 4 } 5}); 6 7$('#text2').on('keyup', function (e) { 8 if (e.keyCode == 13) { 9 $('#text3').focus(); 10 } 11}); 12 13$('#text3').on('keyup', function (e) { 14 if (e.keyCode == 13) { 15 $('#text1').focus(); 16 } 17});
Ⅱ. 実現したいこと
2点あります。
1. 冗長な部分がある
現状、以下のコードはtext1
, text2
, text3
全てほぼ同じ内容であるにも関わらず複数書いているため冗長と感じます。
しかし、どのように書き直せば良いか分かりません。
どのように書けば1つにまとめることができ、汎用性を高める事が出来ますでしょうか?
js
1$('#text1').on('keyup', function (e) { 2 if (e.keyCode == 13) { 3 $('#text2').focus(); 4 } 5});
2. 動的要素の追加に対応できない
追加する
ボタンを押してtext4
とtext5
の合計2つを追加した後に、text4
でEnterキーを押しても反応しません。text1~3
は反応します。
コンソールにエラーが出ない為原因がわからずハマっています。
どのようにすれば動的要素の追加に対応できますでしょうか。
https://jsfiddle.net/ukyrmLxh/
HTML
1<button id="button1">追加する</button> 2 3<div id="inputs"> 4 <input id="text1" type="text" placeholder="1"> 5 <input id="text2" type="text" placeholder="2"> 6 <input id="text3" type="text" placeholder="3"> 7</div>
js
1let input_text_count = 3; 2 3$('#button1').on('click', function (e) { 4 input_text_count++; 5 6 $("<input>", { 7 type: 'text', 8 id: 'text' + input_text_count, 9 placeholder: input_text_count 10 }).appendTo('#inputs'); 11}); 12 13$('#text1').on('keyup', function (e) { 14 if (e.keyCode == 13) { 15 $('#text2').focus(); 16 } 17}); 18 19$('#text2').on('keyup', function (e) { 20 if (e.keyCode == 13) { 21 $('#text3').focus(); 22 } 23}); 24 25$('#text3').on('keyup', function (e) { 26 if (e.keyCode == 13) { 27 $('#text4').focus(); 28 } 29}); 30 31$('#text4').on('keyup', function (e) { 32 if (e.keyCode == 13) { 33 $('#text5').focus(); 34 } 35}); 36 37$('#text5').on('keyup', function (e) { 38 if (e.keyCode == 13) { 39 $('#text1').focus(); 40 } 41});
補足情報(言語/FW/ツール等のバージョンなど)
- Windows 10 64bit
- Chrome 60.0.3112.101(Official Build) (64 ビット)
- jQuery 3.1.1(バージョン制約はありません。)
回答3件
あなたの回答
tips
プレビュー