กล่องโต้ตอบพร้อมท์มีประโยชน์มากเมื่อคุณต้องการให้กล่องข้อความปรากฏขึ้นเพื่อรับข้อมูลของผู้ใช้ ดังนั้นจึงทำให้คุณสามารถโต้ตอบกับผู้ใช้ได้ ผู้ใช้ต้องกรอกข้อมูลในฟิลด์แล้วคลิกตกลง กล่องโต้ตอบนี้จะแสดงขึ้นโดยใช้วิธีการที่เรียกว่า prompt()
ต่อไปนี้เป็นรหัสสำหรับแสดงพรอมต์ใน JavaScript -
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>JavaScript Prompt() method</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to get the prompt dialogue box</h3>
<script>
let resultEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
let res = prompt("Are you sure");
if (res === null) {
resultEle.innerHTML = "You pressed cancel";
} else {
resultEle.innerHTML = "You entered " + res + " in the prompt box";
}
});
</script>
</body>
</html> ผลลัพธ์

เมื่อคลิกที่ปุ่ม 'คลิกที่นี่' และพิมพ์บางอย่างในกล่องพรอมต์ -

เมื่อคลิกตกลงบนกล่องข้อความ -
