常规文本字段,用户输入一个字符串。测试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/
谢谢 唐
@DonG你似乎也提交表格,无论通过验证或不。 Yup; – bfavaretto 2012-04-06 03:36:35
Yup;对于他来说,使用type ='button' - 或 - 在验证失败的路径的验证函数中返回false会更好。 – 2012-04-06 03:37:59
好的,我看到你的观点,我已经将它改为myTextBox.focus();并且仍然不关注输入/文本框。 – DonG 2012-04-06 03:45:42