简体   繁体   English

Javascript阻止表单提交

[英]Javascript prevent form submission

I have a loop that checks if 44 fields are null, and displays an error message for those that are null. 我有一个循环,用于检查44个字段是否为空,并为这些字段显示错误消息。 The issue I'm having is that even if there are null fields, the form submits after about 2 seconds. 我遇到的问题是,即使有空字段,表单也会在大约2秒钟后提交。 How can I prevent form submission if an error is triggered? 如果触发错误,如何防止表单提交?

@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;
          }
      }

Using jQuery: 使用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();
        }
    });
});

Other better approaches would be HTML5 form validation using required : http://www.sitepoint.com/html5-form-validation/ 其他更好的方法是使用required HTML5表单验证: http : //www.sitepoint.com/html5-form-validation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM