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

วิธีแสดง Prompt Dialog Box ด้วย JavaScript

Prompt Dialog Box คืออะไร

กล่องโต้ตอบ (Dialog Box) ที่แสดงช่องกรอกข้อความ เพื่อรับค่าจากผู้ใช้ ผู้ใช้ต้องกรอกข้อมูลแล้วกด OK หรือกด Cancel เพื่อยกเลิก

Syntax: prompt()

var result = prompt(message, defaultValue);
  • message: ข้อความแจ้งเตือน/คำสั่ง (String)
  • defaultValue: ค่าเริ่มต้นในช่องกรอก (String, ไม่บังคับ)

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

  • ผู้ใช้กด OK: คืนค่าข้อความที่กรอก (String)
  • ผู้ใช้กด Cancel หรือปิดกล่อง: คืนค่า null
  • ผู้ใช้กด OK โดยไม่กรอกอะไร: คืนค่า "" (Empty String) หรือ defaultValue

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

<html>
<head>
  <script>
    function getValue(){
      var retVal = prompt("Enter your name : ", "your name here");
      document.write("You have entered : " + retVal);
    }
  </script>
</head>
<body>
  <p>Click the following button to see the result: </p>
  <form>
    <input type="button" value="Click Me" onclick="getValue();" />
  </form>
</body>
</html>

ตัวอย่างปรับปรุง: ตรวจสอบค่าที่รับมา

function getName() {
  var name = prompt("กรุณากรอกชื่อของคุณ:", "");
  
  if (name === null) {
    console.log("ผู้ใช้กด Cancel");
  } else if (name.trim() === "") {
    console.log("ผู้ใช้ไม่ได้กรอกชื่อ");
  } else {
    console.log("สวัสดี " + name + "!");
  }
}

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

  • Prompt เป็น Synchronous Blocking UI: หยุดการทำงานของหน้าเว็บจนกว่าผู้ใช้จะตอบ
  • รูปลักษณ์ขึ้นอยู่กับเบราว์เซอร์ ไปปรับแต่งได้ยาก
  • บางเบราว์เซอร์อาจบล็อก Prompt ถ้าถูกเรียกไม่ได้จาก User Interaction (เช่น ใน setTimeout)
  • ไม่เหมาะสำหรับ UI สมัยใหม่ ควรใช้ Modal Dialog แบบ Custom แทน

สรุป

prompt() ใช้ง่าย สำหรับรับค่าพื้นฐานจากผู้ใช้ แต่มีข้อจำกัดด้าน UI/UX ควรใช้ในกรณีง่ายๆ หรือระหว่างพัฒนา/ทดสอบเท่านั้น