form form submit onclick and onsubmit

 onsubmit can only be used on forms, it will be triggered before submitting the form, onclick is used by controls such as buttons to trigger click events.

Before submitting the form, data validation is generally performed. You can choose to validate in onclick on the submit button or in onsubmit.

But onclick is fired earlier than onsubmit.

  Submission process

1. The user clicks the button ---->

2. Trigger the onclick event ----> 

3. onclick returns true or onclick is not processed ----> 

4. Trigger the onsubmit event ----> 

5. onsubmit is not processed or returns true ------> 

6. Submit the form.

     The onsubmit handler returns false, and the onclick function returns false, which will not cause the form to be submitted.

The first: onsubmit

 

copy code
<script language="javascript">
   function CheckPost ()
   {
      if (addForm.user.value == "")
      {
          alert("Please fill in the username!");
          addForm.username.focus();
          return false;
      }
     if (addForm.title.value.length < 5)
     {
          alert("Title cannot be less than 5 characters!");
          addForm.title.focus();
          return false;
     }
     return true;
   }
</script>

<form action="test.php" method="post" name="addForm"  onsubmit="return CheckPost();">
     <div>用户:<input type="text" size="10" name="user" maxlength="20"/></div>
     <div>标题:<input type="text" name="title" maxlength="50"/></div>
     <div>内容:<textarea name="content" rows="8" cols="30"></textarea></div>
     <div>
           <input type="submit" name="submit" value="发表留言"/>
     </div>
</form>
copy code

 

The second: onclick

copy code
1 <script language="javascript">
 2     function SendForm ()
 3     {
 4         if(CheckPost())
 5         {
 6             document.addForm.submit();
 7         }
 8     }
 9
10     function CheckPost ()
11     {
12          if (addForm.user.value == "")
13          {
14 alert("Please fill in the username!");
15                addForm.username.focus();
16                return false;
17          }
18          if (addForm.title.value.length < 5)
19          {
20 alert("Title cannot be less than 5 characters!");
21                addForm.title.focus();
22                return false;
23          }
24          return true;
25     }
26 </script>
27
28 <form action="test.php" method="post" name="addForm">
29      <div>用户:<input type="text" size="10" name="user" maxlength="20"/></div>
30      <div>标题:<input type="text" name="title" maxlength="50"/></div>
31      <div>内容:<textarea name="content" rows="8" cols="30"></textarea></div>
32      <div><input type="button" name="submit" value="发表留言" onclick="SendForm();"/></div>
33 </form>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326183906&siteId=291194637