การ รวบรวมองค์ประกอบแบบฟอร์ม
ตัวอย่าง
ค้นหาว่ามีกี่องค์ประกอบใน <form> องค์ประกอบที่ระบุ:
var x = document.getElementById("myForm").elements.length;
ผลลัพธ์ของxจะเป็น:
3
ตัวอย่าง "ลองใช้เอง" เพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
คอลเลกชันองค์ประกอบส่งคืนคอลเลกชันขององค์ประกอบทั้งหมดในแบบฟอร์ม
หมายเหตุ:องค์ประกอบในคอลเลกชันจะถูกจัดเรียงตามที่ปรากฏในซอร์สโค้ด
หมายเหตุ:คอลเลกชันองค์ประกอบส่งคืนองค์ประกอบ ทั้งหมด ภายในองค์ประกอบ <form> ไม่ใช่องค์ประกอบ <form> ทั้งหมดในเอกสาร ในการรับองค์ประกอบ <form> ทั้งหมดในเอกสาร ให้ใช้document.formsคอลเลกชันแทน
รองรับเบราว์เซอร์
Collection | |||||
---|---|---|---|---|---|
elements | Yes | Yes | Yes | Yes | Yes |
ไวยากรณ์
formObject.elements
คุณสมบัติ
Property | Description |
---|---|
length | Returns the number of elements in the <form> element. Note: This property is read-only |
วิธีการ
Method | Description |
---|---|
[index] | Returns the element in <form> with the specified index (starts at 0). Note: Returns null if the index number is out of range |
item(index) | Returns the element in <form> with the specified index (starts at 0). Note: Returns null if the index number is out of range |
namedItem(id) | Returns the element in <form> with the specified id. Note: Returns null if the id does not exist |
รายละเอียดทางเทคนิค
รุ่น DOM: | วัตถุเอกสารหลักระดับ 2 |
---|---|
คืนมูลค่า: | ออบเจ็กต์ HTMLFormsControlCollection ที่แสดงองค์ประกอบทั้งหมดในองค์ประกอบ <form> องค์ประกอบในคอลเลกชันจะถูกจัดเรียงตามที่ปรากฏในซอร์สโค้ด |
ตัวอย่างเพิ่มเติม
ตัวอย่าง
[ ดัชนี ]
รับค่าขององค์ประกอบแรก (ดัชนี 0) ในรูปแบบ:
var x = document.getElementById("myForm").elements[0].value;
ผลลัพธ์ของxจะเป็น:
Donald
ตัวอย่าง
รายการ ( ดัชนี )
รับค่าขององค์ประกอบแรก (ดัชนี 0) ในรูปแบบ:
var x = document.getElementById("myForm").elements.item(0).value;
ผลลัพธ์ของxจะเป็น:
Donald
ตัวอย่าง
ชื่อรายการ( id )
รับค่าขององค์ประกอบด้วย name="fname" ในรูปแบบ:
var x = document.getElementById("myForm").elements.namedItem("fname").value;
ผลลัพธ์ของxจะเป็น:
Donald
ตัวอย่าง
วนรอบองค์ประกอบทั้งหมดในรูปแบบและส่งออกค่าของแต่ละองค์ประกอบ:
var x = document.getElementById("myForm");
var txt = "";
var i;
for (i = 0; i < x.length; i++)
{
txt = txt + x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = txt;
ผลลัพธ์ของtxtจะเป็น:
Donald
Duck
Submit
❮ วัตถุแบบฟอร์ม