我有计算表格我想在每个文本框上放置空验证。但问题是警告框在检查第一个框后没有关闭。我想在计算按钮点击之前检查10个字段。
function checkTextField(field) {
if (field.value == 0) {
window.prompt(field.name + "cannot be empty");
field.focus();
return false;
}
return true;
}
<input type="text" class="textfield" value="" id="txt1" name = "Rate " onkeypress="return isNumber(event)" onblur = "checkTextField(this)" autofocus/>
<input class="form-control" id="txt2" name="1" type="number" required onblur = "checkTextField(this)" >
答案 0 :(得分:1)
您的事件之间存在恶性循环,因此每次清除propmt
时,都会生成新的事件。每当用户离开某个字段并且您检测到它无效时,您将焦点设置回它,导致用户刚移动到的任何字段失去焦点,从而导致另一个验证错误。
此外,您现在已经发现为什么alert()
和prompt()
可能是邪恶的,因为它们阻止了用户界面。
更好的方法是在字段旁边的DOM元素中显示一条消息。这不会阻止用户界面。
...而且,不要使用行内HTML事件处理属性(onclick
,onmouseover
等)。使用.addEventListener()
的专用JavaScript。的 Here's why 强>
// Place this code in a <script> element, just before </body>
// Get references to any HTML elements you'll need to work with
var txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");
// Set up event handling functions here, not in the HTML
txt1.addEventListener("blur", validate);
txt1.addEventListener("input", validate);
txt2.addEventListener("blur", validate);
txt2.addEventListener("input", validate);
// This one function is called when either field is having input entered
// or when the user leaves either field.
function validate(evt) {
// All event handling functions are automatically passed a reference to the
// event that they are handling (evt here). From that object, we can get a
// reference to the object that triggered the event (evt.target here).
// Lastly, always call the .trim() string method on user input. It strips
// any leading or trailing spaces off of the inputted value (a common user mistake).
var val = evt.target.value.trim();
var message = ""; // This will hold any error message we wish to show
// Begin validations
if(val === ""){
message = "Can't be empty!";
} else if(isNaN(parseInt(val,10))){
message = "Not a number!"
}
// Place the error message in the element that comes just after the invalid field
evt.target.nextElementSibling.textContent = message
}
&#13;
span.error { color:red; }
&#13;
<!-- Note the empty span elements just after each field... -->
<input type="text" id="txt1" name="Rate" autofocus><span class="error"></span>
<input type="number" id="txt2" name="1" required><span class="error"></span>
&#13;