我有一个循环,检查44个字段是否为空,并显示空值的错误消息。我遇到的问题是,即使有空字段,表单也会在大约2秒后提交。如果触发错误,如何阻止表单提交?
@using (Html.BeginForm("Create", "Table1_1", FormMethod.Post, new { onsubmit = "return validateit()", name = "myForm" }))
{
function validateit() {
var count = 0;
var track = 0;
for (var i = 0; i < fields.length; i++) {
var x = document.forms.myForm[fields[i][0]].value;
if (x === null || x === "" || x === " ") {
count++;
document.getElementById("demo" + (i + 1)).innerHTML = "<font style='color:red';>Error: " + fields[i][1] + "</font>";
track++;
}
else {
document.getElementById("demo" + (i + 1)).innerHTML = "";
track++;
}
if (count > 0 && track > 43) {
return false;
}
}
答案 0 :(得分:0)
使用jQuery:
$(document).ready(function (){
$('.form').submit(function(e){
e.preventDefault();
var formCheck = false;
//check the form here if it is true, send the form
if(formCheck){
$('.form').addClass('checked');
$('.checked').removeClass('form');
$('.checked').submit();
}
});
});
其他更好的方法是使用required
进行HTML5表单验证:http://www.sitepoint.com/html5-form-validation/