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

วิธีใช้ JavaScript แสดง Confirm Message

Confirm Dialog Box คืออะไร

กล่องโต้ตอบยืนยัน (Confirmation Dialog) ใช้ขอความยินยอมจากผู้ใช้ แสดงปุ่มสองปุ่ม: OK และ Cancel

Syntax: confirm()

var result = confirm(message);
  • message: ข้อความแสดงในกล่อง (String)

ค่าที่คืนกลับ

  • ผู้ใช้กด OK: คืนค่า true
  • ผู้ใช้กด Cancel หรือปิดกล่อง: คืนค่า false

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

<html>
<head>
  <script>
    function getConfirmation(){
      var retVal = confirm("Do you want to continue ?");
      if( retVal == true ){
        document.write("User wants to continue!");
        return true;
      } else {
        document.write("User does not want to continue!");
        return false;
      }
    }
  </script>
</head>
<body>
  <p>Click the following button to see the result: </p>
  <form>
    <input type="button" value="Click Me" onclick="getConfirmation();" />
  </form>
</body>
</html>

ตัวอย่างปรับปรุง: ใช้กับการลบข้อมูล

function deleteItem(itemId) {
  if (confirm("คุณแน่ใจหรือไม่ว่าต้องการลบรายการนี้? การกระทำนี้ไม่สามารถยกเลิกได้")) {
    // เรียก API ลบข้อมูล
    fetch('/api/items/' + itemId, { method: 'DELETE' })
      .then(response => {
        if (response.ok) alert("ลบเรียบร้อย");
      });
  } else {
    console.log("ผู้ใช้ยกเลิกการลบ");
  }
}

ข้อจำกัดและข้อควรระวัง

  • เป็น Synchronous Blocking UI เช่นเดียวกับ prompt() และ alert()
  • รูปลักษณ์คงที่ ไม่สามารถปรับแต่ง CSS ได้ (ขึ้นอยู่กับเบราว์เซอร์/OS)
  • ไม่ควรใช้ใน Production UI ที่ซับซ้อน ควรใช้ Custom Modal แทน
  • บางเบราว์เซอร์อาจบล็อกถ้าไม่ได้ Trigger จาก User Action โดยตรง

สรุป

confirm() ใช้สำหรับยืนยันการกระทำสำคัญ (ลบ, ออกจากระบบ, บันทึก) ให้คืนค่า Boolean ทำให้เขียน Logic ง่าย แต่มีข้อจำกัดด้าน UI ควรพิจารณา Custom Modal สำหรับแอปพลิเคชันจริง