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

การใช้งาน Event oninput ใน JavaScript

Event oninput ทริกเกอร์ ทันทีที่ค่าใน Input เปลี่ยนแปลง (Real-time) ต่างจาก onchange ที่รอจน Blur/Enter

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

<!DOCTYPE html>
<html>
  <body>
    <p>Write below:</p>
    <input type="text" id="newInput" oninput="inputFunc()">
    <p id="demo"></p>
    <script>
      function inputFunc() {
        var a = document.getElementById("newInput").value;
        document.write("Typed: " + a);
      }
    </script>
  </body>
</html>

คำอธิบาย

  • ทริกเกอร์: พิมพ์, ลบ, Paste, Drag-Drop, Voice Input, Autofill — ทุกอย่างที่เปลี่ยน Value
  • event.target.value — ค่าปัจจุบัน (ไม่ต้องผ่าน Event Parameter ใน Inline Handler)
  • ไม่ทริกเกอร์จาก Script: input.value = 'x' (ใช้ dispatchEvent(new Event('input')) ถ้าต้องการ)

oninput vs onchange

Eventทริกเกอร์Use Case
inputReal-time (ทุก Keystroke)Live Search, Char Counter, Auto-format
changeBlur/Enter หลังเปลี่ยนค่าForm Submit, Final Validation

รูปแบบมาตรฐานสมัยใหม่

const input = document.getElementById('newInput');
const demo = document.getElementById('demo');

input.addEventListener('input', (e) => {
  demo.textContent = `Typed: ${e.target.value}`;
  // Live Search Debounce
  clearTimeout(input.searchTimer);
  input.searchTimer = setTimeout(() => {
    searchAPI(e.target.value);
  }, 300);
});

รองรับ: <input>, <textarea>, <select>, contenteditable