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

onchange Event ไม่ทำงานกับ Input Type Color ใน JavaScript

onchange บน <input type="color"> ทำงานเมื่อ User เลือกสีเสร็จ (ปิด Color Picker) ไม่ใช่ตอน Drag เลือก

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Color Input onchange</title>
</head>
<body>
  <p>
    <label for="color">Choose Color</label>
    <input type="color" id="selectedColor" value="#985d5d" onchange="showValue(this);" />
  </p>
  <script>
    function showValue(c) {
      console.log("Selected color:", c.value);
      document.body.style.backgroundColor = c.value; // Bonus: เปลี่ยนพื้นหลัง
    }
  </script>
</body>
</html>

คำอธิบาย

  • onchange="showValue(this)" ส่ง Element ให้ Function
  • Event change ยิงเมื่อ: User เลือกสี → กด OK/ปิด Picker (Commit)
  • Event input ยิง Real-time ขณะ Drag เลือกสี (Live Preview)
  • c.value เป็น Hex String เช่น "#ff0000"
  • Default Value: value="#985d5d"

Best Practice

  • ใช้ addEventListener แทน Inline Handler
  • input.addEventListener('input', livePreview) สำหรับ Live Preview
  • input.addEventListener('change', finalValue) สำหรับค่าสุดท้าย

ผลลัพธ์

เลือกสีใน Picker → กด OK → Console Log แสดง Hex Color | Body เปลี่ยนสีตามที่เลือก