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.forms property provides an array-like collection of all forms on the page.
  • forms[0] refers to the first form in the collection.
  • The for loop iterates through each element of the form array.
  • input.type, input.name, and input.value access 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.

JavaScript: Looping Through Form Inputs and Accessing Their Values

原文地址: https://www.cveoy.top/t/topic/oJ8Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录