6

通常のテキスト フィールド、ユーザーが文字列を入力します。a) 入力に何かがあるかどうか、b) 入力に空白がないかどうか、および c) 整数のみで他の文字がないかどうかをテストします。次に、送信ボタン。私は html 動作を使用していないことに注意してください。入力には onclick がなく、コンテンツ/プレゼンテーション/動作の厳密な分離がありません。

私のHTML:

<form name="basicText" id="basicText" action="">
<p>Enter any ol' integer: 
<input type="text" id="inputBox" name="inputBox" size="14"/>    
<input value = "Next...?" type="submit" id="mySubmitBtn" name="mySubmitBtn"/>
</p>
</form>
<script src="js/w1bscript.js" type="text/javascript"></script>

また、すべての要素をロードできるように、外部 JavaScript ファイルが の最後に追加されていることにも注意してください (今はオンロードについて心配する必要はありません)。

JavaScript:

var myButton1 = document.getElementById("mySubmitBtn");
var myForm1 = document.getElementById("basicText");
var myTextBox = myForm1.inputBox;

function submitPress() {
 if(myTextBox.value.length == 0) {
    alert("You didn't enter anything! Once more time, with feeling...")
    basicText.focus();
    basicText.select();
 } else if(/\s/.test(myTextBox.value)) {
    alert("Eh... No spaces. Just integers. Try again...");
    basicText.focus();
    basicText.select();
  } else if (isNaN(myTextBox.value)==true) {
    alert("Eh... Gonna need you to enter ONLY digits this time. kthnx.");
    basicText.focus();
    basicText.select();
 } else {
    // The textbox isn't empty, and there's no spaces. Good.
    alert("you've passed the test!")
  }
}
myButton1.addEventListener('click', submitPress, false);

間違った入力を入力すると、ロジックは機能しますが、使用しているブラウザーに関係なく、カーソルがテキスト ボックスに戻りません。

フィドル: http://jsfiddle.net/2CNeG/

ありがとう、ドン

4

2 に答える 2

9

You will observe that once you have commented your alert box you will be able to see your focus working.But there is a solution for the same. Do try this one.I think it should work.

setTimeout(function() {
      document.getElementById('inputBox').focus();
    }, 0);
于 2012-04-06T03:37:28.117 に答える
4

フォーム要素に焦点を合わせているように見えます。代わりに、テキスト ボックスに集中する必要があります。

document.getElementById('inputBox').focus();

またはmyTextBox.focus()あなたのコードで。

于 2012-04-06T03:29:25.807 に答える