2012-04-06 133 views
6

常規文本字段,用戶輸入一個字符串。測試a)輸入中是否有東西,b)輸入中沒有空白,c)只有整數,沒有其他字符。 然後提交按鈕。 你會注意到我沒有使用html行爲,輸入中沒有onclick,嚴格的Content/Presentation/Behavior分離。javascript焦點()不聚焦

我的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文件的,因此所有元素的末尾添加外部可裝載(不擔心的onload現在)。

中的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

它看起來像你對我的重點是你的表單元素上;您需要專注於文本框:

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

myTextBox.focus()在您的代碼中。

+0

@DonG你似乎也提交表格,無論通過驗證或不。 Yup; – bfavaretto 2012-04-06 03:36:35

+0

Yup;對於他來說,使用type ='button' - 或 - 在驗證失敗的路徑的驗證函數中返回false會更好。 – 2012-04-06 03:37:59

+0

好的,我看到你的觀點,我已經將它改爲myTextBox.focus();並且仍然不關注輸入/文本框。 – DonG 2012-04-06 03:45:42

6

你會發現,一旦你評論了你的警報箱,你將能夠看到你的工作重點。但是有一個相同的解決方案。請嘗試這一個,我認爲它應該工作。

setTimeout(function() { 
     document.getElementById('inputBox').focus(); 
    }, 0); 
+0

是的,我發現重點在那一瞬間,然後消失...... – DonG 2012-04-06 03:44:50