Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ป้องกันไม่ให้ Form โหลดหน้าใหม่ใน JavaScript


สมมติเราต้องการเมื่อผู้ใช้ Submit Form เราจัดการ Event Submit ฝั่ง Client และป้องกัน Browser โหลดหน้าใหม่ทันที

HTML Form

<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() บอก Browser ให้หยุดพฤติกรรมเริ่มต้น และให้เราจัดการ Event Submit ฝั่ง Client เอง

โค้ด 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>