Validation method before form submission - form's onsubmit event

Validation method before form submission - form's onsubmit event

1.1 Overview The
        onsubmit event is only used in form elements. The onsubmit event will be triggered when the submit button in the form is clicked, so it is often used for unified validation before the form is submitted.
1.2 Syntax
        onsubmit = "return false", no submission is performed.
        onsubmit = "return true" or onsubmit = "return", execute the submission.
1.3 Instance
        Instance - Submit Verification:
function submitFun(obj){
    if(obj.category.value == '' "){
        alert("Please enter");
        return false;
    }
}

<form onsubmit="submitFun();">
    <input type="text" name="category" >
    <input type="submit" name="submit" value="提交">
</form>

        In the above example, when the "Submit" button is clicked, the onsubmit event of the form will be triggered, and the function submitFun() will be executed at this time. If submit is empty, prompt for input and return false, i.e. the form will not be submitted.
1.4 Extension - the difference between onsubmit() and submit()
1. Difference
        1" onsubmit() is a js event, which is triggered when the form is submitted; and submit is a method, which is used to submit the form.
        2" The sequence of the two operations: onsubmit() comes first, submit comes after.
2. Example
Js code:
function fun(){
    alert("form submit !");
}

<form onsubmit="fun()">
    <input type="submit" id="aaa" value="submit">
    <input type="button" id="bbb" value="onclick_submit" onclick="document.forms[0].submit();">
</form>

        Note: When the input[type="button"] button is clicked, the form will be submitted, but the function fun() will not be run, because the onsubmit event cannot be triggered in this way. Click the input[type="submit"] button, the form will be submitted and the onsubmit event will be fired.
1.5 Extension - the difference between input[type="submit"] submission and js submission The
        form submission form can be submitted using the input[type="submit"] button, or javascript can be used to submit the form.
Example:
<form action="" method="post" id="form">
    Name: <input type="text" name="username" size="30"><br>
    Email: <input type="text" name="useraddr" size="30"><br>
    Notice: <textarea name="comments" cols="30" rows="5"></textarea><br>
    <input type="button" value="Send Form" onclick=" formSubmit ();">
    <--In general, here is the use of submit-->
</form>

function formSubmit(){
    document.getElementById("form").submit();
}

        To submit the form using js above, you first need to get the form form, and then use the submit() method of js to submit the form to the server. And using the input[type="submit"] button to submit does not need to get the form form.

Guess you like

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