2017-08-27 31 views
-1

前の入力がmaxlength値に達したら、次の入力にフォーカスしようとしています。しかし、私のコードではうまくいきません。javascriptコードはローカルでは動作しませんが、jsfiddleで動作します

<html> 
    <head> 
    <script> 
     var a = document.getElementById("num1"), 
      b = document.getElementById("num2"), 
      c = document.getElementById("num3"); 

     a.onkeyup = function() { 
      if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
       b.focus(); 
      } 
     } 
     b.onkeyup = function() { 
      if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
       c.focus(); 
      } 
     } 
    </script> 
    </head> 

<body> 
    <input type="text" id="num1" maxlength="3"> 
    <input type="text" id="num2" maxlength="2"> 
    <input type="text" id="num3" maxlength="6"> 
</body> 
</html> 
+0

スクリプトは、本体の後にロードされなければならない、または少なくともあなたのロジックは、DOM準備ハンドラ内にラップする必要があります。スクリプトが頭の中にあるので、ボディが完全にロードされたため実行されます。この場合、要素は実行時に利用できません。 – Terry

+0

投稿する前に[検索](/検索?q =%5Bjs%5D +%27t +仕事+しかし+作品+ +フィドルで)してください。 [ここ](/ help/searching)の検索の詳細 –

答えて

0

編集したコードは次のとおりです。

  • 変数の定義の最後にセミコロンが正しくありませんでした。
  • スクリプトを先頭ではなくコードの最後に移動します。定義の時点で要素が存在しなかったため、変数のnullポインティングにつながります。
<html> 
<head> 
    <!--script moved down--> 
</head> 
<body> 
    <input type="text" id="num1" maxlength="3"> 
    <input type="text" id="num2" maxlength="2"> 
    <input type="text" id="num3" maxlength="6"> 

    <script> 
     //semicolon correction here 
     var a = document.getElementById("num1"); 
     var b = document.getElementById("num2"); 
     var c = document.getElementById("num3"); 

     a.onkeyup = function() { 
      if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
       b.focus(); 
      } 
     }; 
     b.onkeyup = function() { 
      if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
       c.focus(); 
      } 
     }; 
    </script> 
</body> 
</html> 
0

問題ではなくコンマで、あなたはセミコロンを追加する必要がありますか、カンマを追加しますがbcからvarを削除することができ、これらの3つの変数を定義してあります。

var a = document.getElementById("num1"); 
 
var b = document.getElementById("num2"); 
 
var c = document.getElementById("num3"); 
 

 
/* 
 
var a = document.getElementById("num1"), 
 
b = document.getElementById("num2"), 
 
c = document.getElementById("num3"); 
 
*/ 
 

 

 
a.onkeyup = function() { 
 
    if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
 
    b.focus(); 
 
    } 
 
} 
 
b.onkeyup = function() { 
 
    if (this.value.length === parseInt(this.attributes["maxlength"].value)) { 
 
    c.focus(); 
 
    } 
 
}
<input type="text" id="num1" maxlength="3"> 
 
<input type="text" id="num2" maxlength="2"> 
 
<input type="text" id="num3" maxlength="6">

関連する問題