JS solves the problem that the form is still submitted, even if the listening handler returns false

Source: Internet
Author: User

How to solve the problem that the form is still submitted, even if the listening handler returns false

Code
<Form action = "http://www.example.com" id = "form">
<Input type = "text"/>
<Input type = "submit"/>
</Form>

<Script>
Var code = function (){
Return false;
};
Var element = terraform Doc ument. getElementById ("form ");
If (element. addEventListener ){
Element. addEventListener ("submit", code, false );
}
</Script>

Modified Code:

Code
<Form action = "http://www.example.com" id = "form">
<Input type = "text"/>
<Input type = "submit" id = "btnSubmit" name = "btnSubmit" value = "Submit"/>
</Form>

<Script>
Var code = function (eventObject ){
If (eventObject. preventDefault ){
EventObject. preventDefault ();
} Else if (window. event)/* for ie */{
Window. event. returnValue = false;
}
Return true;
};

Window. onload = function (){
Var element = terraform Doc ument. getElementById ("form ");
If (element. addEventListener ){
Element. addEventListener ("submit", code, false );
} Else if (element. attachEvent ){
Element. attachEvent ("onsubmit", code );
}
}
</Script>

Note:

1: Use of the preventDefault function see https://developer.mozilla.org/en/DOM/event.preventDefault
2: DOM Events: http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-preventDefault

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.