Table of contents
3 forms of form submission
MDN - When submitting the form, if it is not specified, form.action
the page will be reloaded, otherwise it will jump to form.action
.
<form>
<input type="text" />
</form>
Effect:
1. Submit by default
W3C standard definition:
When there is only 1 single-line text input field in a form , the behavior of pressing Enter (Enter key) in this field should be regarded by the browser as a request to submit the form.
Single line text input field:
input.type
=text
number
password
search
tel
url
2. submit
<form>
<input type="submit" value="提交" />
<!-- 图形化 submit 按钮,表现和 type="submit" 一致 -->
<input type="image" src="./vue.svg" />
</form>
3. button submit
MDN - button , button
the type
default issubmit
<form>
<button>提交</button>
</form>
Block submission
Submitting the form actually executes form.submit
the event, so just prevent the event.
The first two methods are valid for all three submission methods because they are for forms.
Method 1—— return false
<form onsubmit="return false;">
<input type="text" />
</form>
You can also perform form validation in the event function:
<form onsubmit="return validateForm();">
<input type="text">
</form>
<script>
function validateForm() {
if (/* 验证通过 */) {
return true; // 允许表单提交
} else {
return false; // 阻止表单提交
}
}
</script>
Method 2 - Prevent the default behavior of submit
<form id="myForm">
<input type="text">
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
// 阻止默认的表单提交行为
event.preventDefault();
// 在这里可以编写表单验证逻辑
if (/* 验证通过 */) {
this.submit(); // 手动触发表单提交
}
});
</script>
This method is used in vue's event processing .
<!-- 提交事件将不再重新加载页面 -->
<form @submit.prevent="onSubmit"></form>
Method 3 - Processing of buttons
When button
submitting via , button.type = "submit"
the form is submitted directly because of . So type
just modify it.
<form id="myForm">
<input type="text" name="inputField">
<button type="button" onclick="validateAndSubmit()">提交</button>
</form>
<script>
function validateAndSubmit() {
// 在这里编写表单验证逻辑
if (/* 验证通过 */) {
document.getElementById("myForm").submit(); // 手动触发表单提交
}
}
</script>
that's all.