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

JavaScript Dialog Boxes - Alert, Confirm, Prompt


Dialog Boxes แบบ Native ของ JavaScript

JavaScript มี Dialog boxes ในตัว 3 แบบ ใช้สำหรับแจ้งเตือน ยืนยัน และรับข้อมูลจากผู้ใช้

Methodวัตถุประสงค์ปุ่มคืนค่า
alert(message)แจ้งเตือนข้อมูล (One-way)OKundefined
confirm(message)ยืนยันการกระทำ (Yes/No)OK, Canceltrue / false
prompt(message, default)รับข้อความจากผู้ใช้OK, Cancelstring / null

ตัวอย่างโค้ดครบถ้วน

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>JavaScript Dialog Boxes</title>
  <style>
    body { font-family: 'Segoe UI', sans-serif; padding: 20px; max-width: 600px; margin: 0 auto; }
    .btn-group { display: flex; gap: 10px; flex-wrap: wrap; margin: 20px 0; }
    button { padding: 12px 24px; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; font-weight: 500; transition: all 0.2s; }
    .btn-alert { background: #2196F3; color: white; }
    .btn-alert:hover { background: #1976D2; }
    .btn-confirm { background: #FF9800; color: white; }
    .btn-confirm:hover { background: #F57C00; }
    .btn-prompt { background: #7e32d4; color: white; }
    .btn-prompt:hover { background: #6a1b9a; }
    .result { background: #f5f5f5; padding: 20px; border-radius: 8px; min-height: 100px; font-family: monospace; white-space: pre-wrap; }
    .log-entry { margin: 5px 0; padding: 8px; background: white; border-radius: 4px; border-left: 3px solid #7e32d4; }
  </style>
</head>
<body>
  <h1>JavaScript Dialog Boxes</h1>
  <p>ลองกดปุ่มต่างๆ ด้านล่างเพื่อทดสอบ dialog boxes ต่างๆ</p>
  
  <div class="btn-group">
    <button class="btn-alert" id="alertBtn">🔔 Alert Box</button>
    <button class="btn-confirm" id="confirmBtn">❓ Confirm Box</button>
    <button class="btn-prompt" id="promptBtn">⌨️ Prompt Box</button>
  </div>
  
  <h3>ผลลัพธ์:</h3>
  <div class="result" id="result"></div>

  <script>
    const result = document.getElementById('result');
    
    function log(message, type = 'info') {
      const entry = document.createElement('div');
      entry.className = 'log-entry';
      entry.textContent = `[${new Date().toLocaleTimeString('th-TH')}] ${message}`;
      if (type === 'success') entry.style.borderLeftColor = '#4CAF50';
      if (type === 'warning') entry.style.borderLeftColor = '#FF9800';
      if (type === 'error') entry.style.borderLeftColor = '#f44336';
      result.prepend(entry);
    }
    
    // Alert
    document.getElementById('alertBtn').addEventListener('click', () => {
      alert('นี่คือ Alert Box!\nใช้สำหรับแจ้งเตือนข้อมูลเท่านั้น');
      log('alert() ถูกเรียก - ผู้ใช้กด OK', 'info');
    });
    
    // Confirm
    document.getElementById('confirmBtn').addEventListener('click', () => {
      const confirmed = confirm('คุณแน่ใจหรือไม่ว่าต้องการดำเนินการต่อ?');
      if (confirmed) {
        log('confirm() → true (ผู้ใช้กด OK)', 'success');
      } else {
        log('confirm() → false (ผู้ใช้กด Cancel)', 'warning');
      }
    });
    
    // Prompt
    document.getElementById('promptBtn').addEventListener('click', () => {
      const input = prompt('กรุณากรอกชื่อของคุณ:', 'สมชาย');
      if (input === null) {
        log('prompt() → null (ผู้ใช้กด Cancel)', 'warning');
      } else if (input.trim() === '') {
        log('prompt() → "" (ผู้ใช้กด OK แต่ไม่พิมพ์)', 'info');
      } else {
        log(`prompt() → "${input}" (ผู้ใช้พิมพ์: ${input})`, 'success');
      }
    });
  </script>
</body>
</html>

ข้อจำกัดของ Native Dialog Boxes

ข้อจำกัดรายละเอียด
Blocking (Synchronous)หยุด JavaScript execution จนกว่าจะปิด dialog
ไม่สามารถ Style ได้รูปลักษณ์ขึ้นอยู่กับ Browser/OS (ไม่สอดคล้องกับ Design System)
ไม่รองรับ HTMLแสดงข้อความ Plain text เท่านั้น
Mobile UX แย่คีย์บอร์ดบัง, ปุ่มเล็ก, ไม่ Responsive
Accessibility ปัญหาScreen readers อาจไม่อ่านออก หรือ Focus trap ไม่สมบูรณ์
Browser Blockingบราวเซอร์บางตัวบล็อก prompt/confirm อัตโนมัติหากไม่ได้จาก user gesture

ตัวเลือกทันสมัยแทน Native Dialogs (แนะนำ)

1. <dialog> Element (Native HTML5.2+)

<dialog id="myDialog">
  <h3>ยืนยันการลบ</h3>
  <p>คุณแน่ใจหรือไม่? การกระทำนี้ไม่สามารถย้อนกลับได้</p>
  <form method="dialog">
    <button value="cancel">ยกเลิก</button>
    <button id="confirmBtn" value="delete">ลบ</button>
  </form>
</dialog>

<script>
  const dialog = document.getElementById('myDialog');
  document.getElementById('confirmBtn').addEventListener('click', () => {
    dialog.close('delete'); // ส่งค่ากลับ
  });
  dialog.addEventListener('close', () => {
    console.log('Return value:', dialog.returnValue); // "delete" หรือ "cancel"
  });
  // เปิด dialog
  dialog.showModal(); // Modal (มี backdrop, trap focus)
  // หรือ dialog.show() - Non-modal
</script>

ข้อดี: Native, รองรับ ESC, Backdrop (::backdrop), Focus trap, Form integration, Stylable ด้วย CSS

2. Custom Modal Component (Full Control)

function showConfirm({ title, message, onConfirm, onCancel }) {
  const overlay = document.createElement('div');
  overlay.className = 'custom-modal-overlay';
  overlay.innerHTML = `
    
  `;
  // ... event listeners, append to body, focus management, animation
}

3. Libraries แนะนำ

  • SweetAlert2 (Swal) - สวย, feature-rich, Promise-based
  • Radix UI Dialog - Headless, Accessible, Unstyled
  • Headless UI Dialog - React/Vue, Accessible
  • Material UI Dialog - ถ้าใช้ MUI

เมื่อไหร่ควรใช้ Native Dialogs?

  • Prototyping / Demo เร็วๆ
  • Internal tools / Admin pages
  • Simple debugging (alert สำหรับ debug)
  • Critical errors ที่ต้อง block UI ทันที

Best Practices

  • ไม่ใช้ alert() สำหรับ Error handling ใน Production (ใช้ Toast/Notification แทน)
  • confirm() ใช้เฉพาะการกระทำที่อันตราย (Delete, Logout, Payment)
  • prompt() หลีกเลี่ยงใน Production - ใช้ Custom Form/Modal แทน
  • ทดสอบบน Mobile จริงเสมอ