จับ Event Click ปุ่ม Submit และแสดง Alert
ใช้ jQuery .click() ผูก event ให้ปุ่มด้วย ID
ตัวอย่างโค้ดเต็ม
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Submit Alert</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
CollegeId=<input id="collegeId" type="text"><br />
CollegeName=<input id="collegeName" type="text"><br />
<button id="submitForm">Submit</button>
<script>
$("#submitForm").click(function() {
alert("The Form has been Submitted.");
});
</script>
</body>
</html>
วิธีรัน
บันทึกเป็น index.html แล้วเปิดด้วย Live Server
คำอธิบาย
$("#submitForm")เลือก element id="submitForm".click(handler)ผูก event click (shortcut ของ .on('click', ...))alert()แสดงกล่องข้อความเบราว์เซอร์
แนวทางปัจจุบัน: ใช้ submit event ของ form
<form id="myForm">
<input name="collegeId">
<input name="collegeName">
<button type="submit">Submit</button>
</form>
<script>
$("#myForm").on("submit", function(e) {
e.preventDefault(); // ป้องกัน submit จริง
alert("Form submitted!");
// ทำ AJAX หรือ validation ที่นี่
});
</script>