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

HTML Form Action และ OnSubmit Validation ด้วย JavaScript

ใช้ onsubmit="return validateFunction()" ป้องกัน Submit ถ้า Validation ไม่ผ่าน

ตัวอย่างโค้ด

<!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 onsubmit="return validateTheForm()" method="GET" action="https://mail.google.com/mail/">
        <br/>
        <input type="text" id="txtInput" value=""/>
        <input type="submit" value="search"/>
    </form>

    <script>
        function validateTheForm() {
            var validation = (document.getElementById('txtInput').value == 'gmail');
            if (!validation) {
                alert('Something went wrong...Please write gmail in text box and click');
                return false;
            }
            return true;
        }
    </script>
</body>
</html>

วิธีรันโปรแกรม

  1. บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
  2. คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor

ผลลัพธ์

  • กรอก "gmail" กด Search → Redirect ไป Gmail
  • กรอกค่าอื่น → Alert แจ้งเตือน ไม่ Submit Form