Home > Article > Web Front-end > The reason why form.submit() in JS cannot submit the form
This article mainly introduces the error reason why form.submit() in JS cannot submit the form. The final conclusion of this article is that you should not use submit for the ID and name of the button. Friends in need can refer to it
Go directly to the code:
<p id="register"> <h4>会员注册</h4> <p class="formp"> <form method="post" action="register.php?action=register" name="register" id="registerForm"> <dl> <dt>请认真填写以下内容</dt> <dd class="hasspan"> 用户名:<input type="text" name="username"> </dd> <dd class="hasspan"> 密码:<input type="password" name="pwd"> </dd> <dd class="hasspan"> 确认密码:<input type="password" name="pwdagain"> </dd> <dd id="tximg"> <img src="img/face/m01.gif" alt="选择头像" id="faceimg"> <input type="hidden" name="touxiang" value=""> <label id="imgsrclabel">m01.gif</label> </dd> <dd style="margin-right:120px;"> 验证码:<input type="text" name="code"> <span> <img src="code.php" alt="code" id="code" name="code"> <a href="#code" id="change">换一张</a> </span> </dd> <dd class="btns"> <input type="button" name="submit" id="submit" value="注册"> <input type="button" name="quit" id="quit" value="退出"> </dd> </dl> </form> </p> </p>
Submit the form data to this page, the following is js processing
/*注册表单提交*/ function formDeal() { var btnSubmit = document.getElementById('submit'); var formId = document.getElementById('registerForm'); btnSubmit.onclick = function() { //表单的submit()方法不能提交表单 formId.submit(); } }
If the form is submitted, there will be a prompt message on this page
if(!empty($_GET['action']) && $_GET['action'] == 'register') { echo '你提交了数据'; exit(); }
The result is that I haven’t seen the prompt message after testing for a long time. I thought it was because the code was wrong or the method was written wrong. I checked carefully and checked the official results document to confirm that there was no error.
formId.submit() cannot be submitted, so I had to change the type of btnSubmit to submit for the time being
this.type="submit"
I checked the information online, and the reason boiled down to two points:
1. The form cannot have the tag name="submit"
2. The form cannot be missing "enctype="multipart/form-data""
After testing, these two points are Ridiculous, it didn’t solve my problem (maybe my problem environment is different)
Later, I thought forum friends suggested that I change the ID of the registration button to a different name without submitting. After the correction, the form is submitted normally and the prompt message appears.
Final summary: Do not set the id of the button to submit, otherwise it may cause confusion and cause the submit() method of the form to fail to submit the form. When naming the ID, it is best not to duplicate the name with the existing API to avoid unnecessary annoyance.