Alert Dialog Box เป็นกล่องโต้ตอบแบบ Modal ที่แสดงข้อความเตือนหรือแจ้งเตือนให้ผู้ใช้ มีปุ่ม OK เพียงปุ่มเดียว ใช้สำหรับ:
- แจ้งเตือนข้อผิดพลาด/คำเตือน (Validation)
- แสดงข้อมูลสำคัญที่ต้องการให้ผู้ใช้อ่าน
- Debugging แบบง่าย (แทน console.log)
ไวยากรณ์
alert(message); // หรือ window.alert(message);
ตัวอย่างโค้ด
<html>
<head>
<script>
function Warn() {
alert("This is a warning message!");
document.write("This is a warning message!");
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>
ลักษณะการทำงาน
- Synchronous & Blocking: หยุด JavaScript Execution จนกว่าจะกด OK
- Modal: บล็อกการโต้ตอบกับหน้าเว็บทั้งหน้า
- ไม่สามารถปรับแต่ง UI ได้: ขึ้นอยู่กับ Browser/OS (ไม่ Style ได้)
- ไม่มี Return Value: คืนค่า
undefinedเสมอ
ตัวอย่างการใช้งานจริง
1. Form Validation
function validateForm() {
const email = document.getElementById('email').value;
if (!email.includes('@')) {
alert('กรุณากรอกอีเมลที่ถูกต้อง');
return false; // ป้องกัน Submit
}
return true;
}
2. Debugging
function processData(data) {
alert('Debug: data = ' + JSON.stringify(data)); // ดูค่าระหว่างทำงาน
// ...
}
3. ยืนยันการกระทำ (Confirm ดีกว่า)
// Alert - แค่แจ้ง
alert("Record deleted!");
// Confirm - มีตัวเลือก Yes/No (ดีกว่าสำหรับยืนยัน)
if (confirm("Delete this record?")) {
deleteRecord();
}
ข้อจำกัดและแนวทางปฏิบัติ
- ไม่ควรใช้ใน Production สำหรับ UX ที่ดี (ใช้ Custom Modal/Toast แทน)
- Browser บางตัวบล็อก Alert ถ้าถูกเรียกจาก Event ที่ไม่ใช่ User Interaction
- ใน Node.js ไม่มี
alert(ใช้console.logแทน) - ESLint Rule:
no-alertมักถูกเปิดเพื่อป้องกันการใช้งาน
ตัวเลือกที่ดีกว่า (Modern Alternatives)
- Custom Modal: Bootstrap Modal, SweetAlert2, React Modal
- Toast/Notification: Toastr, Notyf, React Toastify
- Console:
console.log,console.warn,console.error(สำหรับ Dev) - HTML5 Validation:
required,pattern,type="email"(No JS needed)