The onclick and onsubmit of the form.

Reprinted from: https://www.cnblogs.com/huangjinyong/p/9467544.html
https://www.cnblogs.com/huangjinyong/p/9467544.html


I recently encountered a filtering process for processing form data. I used the button's onclick event to check and found that the form was still submitted after the return false.

So I carefully studied the relationship and difference between onclick, onsubmit, and submit aggregate functions.

onsubmit:
You can override this event by returning false in the event handler.
Use this capability to validate data on the client side to prevent invalid data from being submitted to the server.
If the event handler is called by the onsubmit attribute of the form object,
the code must explicitly request the return value using the return function,
and the event handler must provide an explicit return value for each possible code path in the event handler function.
The submit method does not invoke the onsubmit event handler.

submit:
The submit method does not invoke the onsubmit event handler.
Call the onsubmit event handler directly.
When using Microsoft? Internet Explorer 5.5 and later,
you can call the fireEvent method with a value of onsubmit in the sEvent parameter.
首先生成一个form

<form action="#" method="POST" name="A" onsubmit="return X();">
<input type="text" value="" />
<input onclick="Y()" type="submit" value="提交" />
</form>

Write the X() and Y() functions yourself, we will find that the execution order of these functions

  1. onclick: Y ();

  2. onsubmit: X();

  3. submit();

In other words

As long as onclick does not return false, then continue to execute onsubmit

As long as onsubmit does not return false, the form is submitted

Pay attention to the other point of writing

If it is written in js code,, button.onclick=function(){}or button.onclick=函数名; then write the return value directly in the function body.

If it is written directly in the attribute of the label, you must "return X();" to get the return value of the function, otherwise it just calls the function and the return value is not passed

Correct writing:<input type=submit onclick="return X();">
//X() 返回false后,form的submit会被终止

Wrong writing:
<input type=submit onclick="X()">

X() 返回false后未传递给onclick事件,form的submit会继续

Guess you like

Origin blog.csdn.net/wx_assa/article/details/107668932