JavaScript: Looping Through Form Inputs and Accessing Their Values
This code snippet demonstrates how to loop through the inputs of the first form on a web page and access their attributes using JavaScript.
Original Code (with error):
var form = window.document.forms{0] for (var i = 0; i = form.length; i++) {
var input = form[i];
console.log(input.type, input.name, input.value);
}
Corrected Code:
var form = window.document.forms[0];
for (var i = 0; i < form.length; i++) {
var input = form[i];
console.log(input.type, input.name, input.value);
}
Explanation:
- The
window.document.formsproperty provides an array-like collection of all forms on the page. forms[0]refers to the first form in the collection.- The
forloop iterates through each element of theformarray. input.type,input.name, andinput.valueaccess the type, name, and value of each form input, respectively.console.log()displays the extracted information in the browser's console.
This corrected code snippet allows you to easily extract and manipulate information from form inputs, making it a valuable tool for form validation, data processing, and user interaction.
原文地址: https://www.cveoy.top/t/topic/oJ8Q 著作权归作者所有。请勿转载和采集!