Prevent the default submit event of a form

Once the form is clicked on the submit button (submit), it will inevitably jump to the page. If the action of the form is empty, it will also jump to its own page, that is, the effect is to refresh the current page. 
As follows, you can see that when the submit button is clicked, the refresh button of the browser flashes:

write picture description here

If you want to prevent the default submit event of a form, there are several ways:

1. Change <input>the button type in the label from type="submit"totype="button"

2. <button>When the type is not specified in the form, the default type is submit, which can be explicitly modified <button type="button">to prevent form submission

3. Use the preventDefault() method:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        function func(event){
            event.preventDefault();
        }
    </script>
</head>
<body>
    <form action="">
        <input type="submit" value="button" onclick="func(event)" />
    </form>
</body>
</html>
4. Use the onclick click event to return false. Let  's
talk about the form submit button onclick event: 
onclick="return true"  for the default form submission event, 
onclick="return false" in order to prevent the form submission event 
, generally using onclick to call the function has no return value, so generally after the call is completed, the default return true; so you will see that the callback function is processed first and then the form submission jump is performed.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        function func(){
            return false;
        }
    </script>
</head>
<body>
    <form action="">
        <input type="submit" value="button" onclick="return func()" />
        <!--Note that the onclick is return func(); instead of simply calling the func() function-->
    </form>
</body>
</html>
5. Use the onsubmit event  of the form Note: The onsubmit event is used for the object , so adding the onsubmit event to the submit button has no effect. The onsubmit event of the form object is similar to onclick, which is to process the called function first, and then judge whether the form jumps the Boolean value. The   default form submission event  is the blocking form submission event.
<form>  

onsubmit="return true"
onsubmit="return false"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        function func(){
            return false;
        }
    </script>
</head>
<body>
    <form action="" onsubmit="return func()">
        <input type="submit" value="button" />
    </form>
</body>
</html>



Guess you like

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