मान लीजिए हमें यह प्राप्त करना है कि जब उपयोगकर्ता इस HTML फॉर्म को सबमिट करता है, तो हम क्लाइंट साइड पर सबमिट इवेंट को हैंडल करते हैं और ब्राउजर को फॉर्म सबमिट होते ही रीलोड होने से रोकते हैं।
HTML फॉर्म
<form name="formcontact1" action="#"> <input type='text' name='email' size="36" placeholder="Your e-mail :)"/> <input type="submit" name="submit" value="SUBMIT" onclick="ValidateEmail(document.formcontact1.email)" /> </form>
अब, ऐसा करने का सबसे आसान और विश्वसनीय तरीका है हमारे ValidateEmail() फ़ंक्शन को इसकी परिभाषा के शीर्ष पर निम्नलिखित लाइन शामिल करके संशोधित करना:
function ValidateEmail(event, inputText){ event.preventDefault(); //remaining function logic goes here }
preventDefault() ब्राउजर को उसका डिफ़ॉल्ट व्यवहार रोकने और हमें फॉर्म सबमिट इवेंट को क्लाइंट साइड पर ही हैंडल करने देता है।
इसके लिए पूरा HTML कोड है:
उदाहरण
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form name="formcontact1" action="#"> <input type='text' name='email' size="36" placeholder="Your e-mail :)"/> <input type="submit" name="submit" value="SUBMIT" onclick="ValidateEmail(document.formcontact1.email)" /> </form> <script> { function ValidateEmail(event, inputText){ event.preventDefault(); //remaining function logic goes here } } </script> </body> </html>