JavaScript实现表单提交的两种常见方式详解

作者:闭包旅人

时间:2026-10-30

浏览:314

本文详细解析了JavaScript中两种表单提交模式:一是利用原生submit按钮触发onsubmit事件进行验证;二是通过JS绑定点击事件,在调用form.submit()前执行自定义验证逻辑。文章通过代码示例对比了两种方式的实现细节及注意事项,帮助开发者根据需求选择合适方案。

文章目录

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

原生Submit按钮提交方式

第一种方式是使用原生的提交按钮。


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

当点击该button时,会执行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("请填写正确的身份证号码!");
   }
  }
 });*/
 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("此身份证已报名!");
   }
  }
 });
  return flag;
}

在此过程中可以执行各种复杂的验证逻辑。

JavaScript模拟提交方式

第二种方式是通过JavaScript动态设置提交行为。


<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();
   }
});

我们需要通过JS触发实际的提交事件。

如果直接使用onsubmit="return loginForm();"往往无法达到预期效果,因为无论loginForm()返回false还是true,表单都可能被提交。因此,必须在真正发起HTTP请求之前,手动执行验证步骤。


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

如果在JS逻辑中返回false,则不调用submit方法,从而阻止提交。

以上就是处理表单提交前验证的两种主要方式。

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript查找算法技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript中json操作技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》及《JavaScript数学运算用法总结》

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

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章