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

การทำงานกับ document.forms ใน JavaScript

Property document.forms คืนค่า HTMLCollection ของ Element <form> ทั้งหมดในเอกสาร ใช้ .length เพื่อนับจำนวน

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

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript Example</title>
  </head>
  <body>
    <h1>Employee Information</h1>
    <form>
      Name: <input type="text" name="name" value="Amit"><br>
      Subject: <input type="text" name="sub" value="Java">
    </form>
    <h1>Department Information</h1>
    <form>
      DepartmentID: <input type="text" name="dptid" value="D001"><br>
      Dept Name: <input type="text" name="dname" value="Marketing">
    </form>
    <script>
      var num = document.forms.length;
      document.write("<br>How many forms? " + num);
    </script>
  </body>
</html>

คำอธิบาย

  • document.forms — Live HTMLCollection ของ <form> Elements
  • .length — จำนวน Form ทั้งหมด
  • ผลลัพธ์: How many forms? 2
  • เข้าถึง Form: document.forms[0] (Index) หรือ document.forms['name'] (Name Attribute)

การใช้งานจริง

  • Validate ทุก Form: Array.from(document.forms).forEach(form => form.addEventListener('submit', validate))
  • Reset ทุก Form: document.forms[i].reset()
  • เข้าถึง Field: document.forms['formName'].elements['fieldName'].value
  • FormData: new FormData(document.forms[0])

ตัวเลือกสมัยใหม่: document.querySelectorAll('form') คืน NodeList รองรับ Selector ซับซ้อน