首页 > 解决方案 > 表单字段提交

问题描述

我有我的 HTML 和 JS,我将如何在我的 JS 中使用此表单,因此如果未输入其中一个字段,则表单不会提交并显示我的原件请输入所有字段错误

形式:

 <form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">

HTML:

    <!doctype html>
    <html lang="en">
    <head>
      <title> Forms </title>
      <style>
        span {
          padding-left: 10px;
          display: block;
          float: left;
          width: 20%;
        }
        button { margin-left: 10px; }
        body {
          width: 80%; margin: auto; font-family: sans-serif;
          border: 1px solid black;
        }
      </style>
      <meta charset="utf-8">
      <script src="prototype.js"></script>
      <script src="forms.js"></script>
    </head>
    <body>
      <h1> Keyboard  Events and Form Submit </h1>
<!-- Form -->
      <form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
      <p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
      <p> <span>Id:</span> <input id="input2" value=""
      placeholder="Enter ID" name="ID"></p>
      <p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
      <p>
      <button id="submitButton" type="button"  onclick="submit()"> Submit </button>
      <button id="resetButton" type="button"  onclick="reset()"> Reset </button>
      </p>
      <p style="color:red" id="ErrorMessage"> </p>

    </body>
    </html>

JS:

function reset(){
  document.getElementById('input1').value = "";
  document.getElementById('input2').value = "";
  document.getElementById('input3').value = "";
  document.getElementById('ErrorMessage').innerHTML = "";
}

function submit(){
  var inp1 = document.getElementById('input1').value;
  var inp2 = document.getElementById('input2').value;
  var inp3 = document.getElementById('input3').value;
  if(inp1 == "" || inp2 == "" || inp3 == "")
  {
  document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
  }
  else{
  //do your code here
  document.getElementById('ErrorMessage').innerHTML = "";
  }
}

标签: javascripthtmlforms

解决方案


将按钮类型更改为“提交”并在 onsubmit 事件处理程序中进行验证:

<form onsubmit="return validateMethod()" />

将所有验证逻辑移入 validateMethod,如果验证失败则返回 false。

下面是一个示例,但我认为您应该为此使用 jquery 库:

function validateMethod(){
  var inp1 = document.getElementById('input1').value;
  var inp2 = document.getElementById('input2').value;
  var inp3 = document.getElementById('input3').value;
  if(!inp1 || !inp2 || !inp3)
  {
     document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
     return false;
  }
  else{
      //do your code here
      document.getElementById('ErrorMessage').innerHTML = "";
      return true;
  }
}

推荐阅读