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

วิธีเคลียร์/รีเซ็ตฟอร์มด้วย JavaScript

ใช้เมธอด reset() ของฟอร์มเพื่อเคลียร์ค่าทั้งหมด ทำงานเหมือนกดปุ่ม Reset

ตัวอย่าง

<!DOCTYPE html> <html>
  <head>
    <title>Reset HTML form</title>
  </head>
  <body>
    <form id="newForm">
      Student Name<br><input type="text" name="sname"><br>
      Student Subject<br><input type="password" name="ssubject"><br>
      <input type="button" onclick="newFunction()" value="Reset">
    </form>
    <script>
      function newFunction() {
        document.getElementById("newForm").reset();
      }
    </script>
  </body>
</html>

วิธีอื่นๆ

  • ปุ่ม Reset แบบ built-in: <input type="reset" value="Clear Form"> (ไม่ต้องเขียน JS)
  • ล้างเฉพาะบางฟิลด์: document.getElementById('fieldId').value = '';
  • ล้างฟอร์มทั้งหมดด้วย querySelector: document.querySelector('form').reset();

ข้อควรระวัง: reset() จะคืนค่าเป็นค่า เริ่มต้น (defaultValue) ไม่ใช่ค่าว่างเสมอไป หาก input มี value="default" จะกลับเป็นค่านั้น