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

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

Event onreset ทริกเกอร์เมื่อ Form ถูก Reset (กด <input type="reset"> หรือเรียก form.reset())

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

<!DOCTYPE html>
<html>
  <body>
    <script>
      function resetFunct() {
        alert("The form was reset");
      }
    </script>
    <form onreset="resetFunct()">
      Enter age: <input type="number"><br>
      Enter birth month: <input type="text"><br>
      <input type="reset">
    </form>
  </body>
</html>

คำอธิบาย

  • ทริกเกอร์: User กด Reset Button, หรือ form.reset() จาก JS
  • คืนค่า Form Fields เป็นค่าเริ่มต้น (Initial Value จาก HTML value attribute)
  • ไม่ทริกเกอร์: form.submit(), JavaScript set value, input.value = ''

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

const form = document.querySelector('form');
form.addEventListener('reset', (e) => {
  console.log('Form reset');
  // Clear Custom Error Messages
  form.querySelectorAll('.error').forEach(el => el.remove());
  // Reset Custom UI (Character Counters, etc.)
  form.querySelectorAll('[data-counter]').forEach(el => el.textContent = '0');
});

// Programmatic Reset
document.getElementById('resetBtn').addEventListener('click', () => {
  form.reset(); // ทริกเกอร์ reset event
});

Reset vs Clear

ActionMethodทริกเกอร์ onresetค่าที่กลับไป
Reset Button<input type="reset">✅Initial HTML Value
JS Resetform.reset()✅Initial HTML Value
Clear Fieldsinput.value = ''❌Empty String

ใช้เมื่อไหร่: Cleanup Custom UI, Clear Error States, Analytics (User Gave Up)