สมมติว่าสิ่งที่เราต้องบรรลุคือเมื่อผู้ใช้ส่งแบบฟอร์ม 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
} ป้องกันค่าเริ่มต้น () อะไรทำคือการบอกให้เบราว์เซอร์ป้องกันพฤติกรรมเริ่มต้นและปล่อยให้เราจัดการเหตุการณ์ที่ส่งแบบฟอร์มในฝั่งไคลเอ็นต์เอง
รหัส 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>