2012-04-06 137 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