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

สร้าง Alert Box ด้วย JavaScript

Alert Box คืออะไร?

Alert Box คือหน้าต่างเล็กๆ ที่โผล่ตอบสนอง user interaction (คลิก, スクロール, พิมพ์) ใช้เตือนปัญหา หรือแจ้งข้อมูล

ตัวอย่างทั่วไป: user กด submit แต่ลืมกรอก required field → alert แจ้งปัญหา

สร้าง Alert Box ด้วย JavaScript

สร้าง Alert Box

สร้างปุ่มเป็น trigger:

<button onclick="missingFieldWarningPopup()">Submit form</button>

เพิ่ม JS function ใน .js file:

function missingFieldWarningPopup() {
  alert("You forgot to fill out all the required input fields!");
}

การทำงาน: ปุ่มมี onclick attribute เป็น click trigger คลิก → เรียก missingFieldWarningPopup() → โชว์ alert() prompt พร้อมข้อความ

ถ้าอยากเขียน inline ใน <head>:

<script type="text/javascript">
  function missingFieldWarningPopup() {
    alert("You forgot to fill out all the required input fields!");
  }
</script>