複数のinput要素への入力を連続して行う場合、Tabキーでフォーカスを移動することになりますが、elements.focus()を使ってこれを自動的に行う事が出来ます。
ただし、input要素のvalue値を入力(Enterキーを押す)した後のタイミングでフォーカスを動かそうとすると、input要素のindexを使ってキー入力されたinput要素のindex値よりも大きい(:gt(index))、最初の要素(:first)に対しfocusするとコーディングします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | <!DOCTYPE html> < html lang = "UTF-8" > < head > < meta charset = "UTF-8" > < title >YMFB_placeholder</ title > < style > #wrapper{width: 380px;} textarea{width: 370px;} dt{background: lightblue; padding:4px; margin-top:8px;} dd{margin:2px;} </ style > < script type = "text/javascript" src = "C:\0 JavaScript\jQuery\jquery-3.1.0.min.js" charset = "utf-8" ></ script > < script type = "text/javascript" > // 住所入力 html5 function onButtonClick() { var jyusho = document.getElementById("output"); jyusho.innerHTML = document.getElementById("add1").value + document.getElementById("add2").value; } function onButtonClickJQ() { var jyushoJQ = document.getElementById("outputJQ"); jyushoJQ.innerHTML = document.getElementById("add1JQ").value + document.getElementById("add2JQ").value; } $(function(){ // var elements = "input[type=text]"; var elements = "input"; $(elements).keypress(function(e) { var c = e.which; if (c == 13) { var index = $(elements).index(this); if( (index == 2) || (index == 5) ) { onButtonClick(); } else { $(elements + ":gt(" + index + "):first").focus(); e.preventDefault(); } } }); }); </ script > < script type = "text/javascript" src = "C:\0 JavaScript\jQuery\jquery.ah-placeholder.js" charset = "utf-8" > $(function() { $('.jq-placeholder').ahPlaceholder({ placeholderColor : 'silver', placeholderAttr : 'title', likeApple : false }); }); </ script > </ head > < body > < div id = "wrapper" > < h1 >住所入力</ h1 > < dl > < dt >HTML5なら</ dt > < dd >< input type = "text" id = "add1" placeholder = "都道府県を入力してください。" ></ dd > < dd >< input type = "text" id = "add2" placeholder = "番地を入力してください。" ></ dd > < dd >< input type = "button" id = "btn_done" value = "確定" onclick = "onButtonClick();" ></ dd > < dd >< div id = "output" ></ div ></ dd > </ dl > < dl > < dt >jqueryなら</ dt > < input type = "text" id = "add1JQ" value = "" placeholder = "都道府県を入力してください。" >< br > < input type = "text" id = "add2JQ" value = "" placeholder = "番地を入力してください。" > < dd >< input type = "button" id = "btn_placeholderJQ" value = "確定" onclick = "onButtonClickJQ();" ></ dd > < dd >< div id = "outputJQ" ></ div ></ dd > </ dl > </ div > </ body > </ html > |
※なお、e.preventDefault();は、その要素のイベントをキャンセルしている。