JS两种类型的表单提交方法实例分析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JS两种类型的表单提交方法实例分析

巴霍巴利   2020-05-15 我要评论

本文实例分析了JS两种类型的表单提交方法。分享给大家供大家参考,具体如下:

1.原始的

<form method="post" action="/student/stureg/add" id="form1" onsubmit="return subForm();">
<button type="submit" class="button red" style="font-size:18px; font-family:'微软雅黑';">提 交</button>

这里的button提交之后,执行subForm()方法,subForm可以对表单进行验证,返回false,表单不提交。否则提交。

function subForm()
{
  var flag = true;
  $(".required").each(function(){
    if(!$(this).val())
    {
      flag = false;
      $(this).css({ border: "1px solid #F56939",borderRadius:"5px",color:"#F56939",height:"26px"});
      $(this).attr("status","1").val("此处为必填项,请您填写!");
    }
  });
 /*$(".idCardNo").each(function(){
  if(!idCardNo($(this).val()))
  {
   flag = false;
   $(this).css({ border: "1px solid #F56939",borderRadius:"5px",color:"#F56939",height:"26px"});
   if($(this).attr("status")!=1){
    $(this).attr("status","1").val("请填写正确的SFZ号码!");
   }
  }
 });*/
 var reg = new RegExp("^[0-9]*$");
 $(".number").each(function(){
  if(!reg.test($(this).val()))
  {
   flag = false;
   $(this).css({ border: "1px solid #F56939",borderRadius:"5px",color:"#F56939",height:"26px"});
   if($(this).attr("status")!=1){
    $(this).attr("status","1").val("请填写正确的联系电话!");
   }
  }
 });
 $(".exCardNo").each(function(){
  if(exCardNo($(this).val())==1)
  {
   flag = false;
   $(this).css({ border: "1px solid #F56939",borderRadius:"5px",color:"#F56939",height:"26px"});
   if($(this).attr("status")!=1){
    $(this).attr("status","1").val("此SFZ已报名!");
   }
  }
 });
  return flag;
}

各种验证!

2.js设置的提交

<form method="post" action="/student/stureg/reglogin" id="form_login">
<a id="submit"><img src="/images/login/login_bt.png" style="cursor:pointer"/></a>

这里并不是提交按钮,而是一个模拟提交的按钮。

$("#submit").click(function(){
   if(loginForm())
   {
     $("#form_login").submit();
   }
});

触发提交事件,这里用

onsubmit="return loginForm();"就没效果了,不管是否返回false都会提交。所以要在真正提交之前,做一下验证。

function loginForm(){
 var flag = true;
 $(".notnull").each(function(){
  if(!$(this).val())
  {
   flag = false;
   $(this).css({ border: "1px solid #F56939",borderRadius:"5px",color:"#F56939",height:"26px"});
   $(this).attr("status","1").val("不能为空");
  }
 });
 return flag;
}

返回false,就不调用submit方法。

这就是两种处理表单提交前奏的方式。

希望本文所述对大家JavaScript程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们