การสร้างเว็บฟอร์ม งานที่พบบ่อยคือการดึงค่าจาก dropdown (select element) บทความนี้สอนวิธีทำด้วย JavaScript
Dropdown HTML Element
ใช้ tag <select> และ children <option>
<select name="fruits" id="fruits"> <option value="">--select--</option> <option value="avocado">Avocado🥑</option> <option value="watermelon">Watermelon🍉</option> <option value="kiwi">Kiwi🥝</option> <option value="tomato">Tomato🍅</option> </select> <h2 id="pick"></h2>
สำคัญ: attribute value คือข้อมูลสำหรับ JavaScript ข้อความใน option tag แสดงให้ user เห็น ไน่พวกใช้ใน logic
เลือกและแสดงค่า Dropdown ด้วย JavaScript
const element = document.getElementById("fruits");
const checkValue = element.options[element.selectedIndex].value;
const checkText = element.options[element.selectedIndex].text;
เข้าถึง options array, เลือก selectedIndex แล้วอ่าน value หรือ text
ฟังเหตุการณ์เปลี่ยนแปลง (Event Listener)
ทำให้ dropdown dynamic ด้วย addEventListener
element.addEventListener("change", (e) => {
const value = e.target.value;
const text = element.options[element.selectedIndex].text;
if (value) {
document.getElementById("pick").textContent = `Value Selected: ${value}`;
} else {
document.getElementById("pick").textContent = "";
}
});
ตอนนี้เลือก option ใดก็ได้ JavaScript จะตอบสนองและอัปเดต h2 ทันที
สรุป
การดึงค่า dropdown เป็นทักษะสำคัญในเว็บพัฒนา ค่าที่ได้ใช้สำหรับ update database, แสดงให้ user เห็น หรือ react กับ DOM changes JavaScript ทำได้ง่ายและรวดเร็ว