Get data from input fields as object

Here’s an example of how you can select all input fields in HTML using JavaScript and store their values in an object:

HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Input Fields Example</title>
</head>
<body>
  <input type="text" id="name" placeholder="Name">
  <input type="text" id="email" placeholder="Email">
  <input type="text" id="phone" placeholder="Phone Number">
  <button onclick="collectInputs()">Submit</button>

  <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

function collectInputs() {
  // Create an empty object to store the input values
  var inputValues = {};

  // Get all input elements using the querySelectorAll method
  var inputs = document.querySelectorAll('input');

  // Iterate through each input element
  inputs.forEach(function(input) {
    // Get the ID of the input element
    var id = input.id;

    // Get the value entered by the user
    var value = input.value;

    // Store the value in the object using the ID as the key
    inputValues[id] = value;
  });

  // Log the collected input values
  console.log(inputValues);
}

In this example, we first create an empty object called inputValues to store the input values. Then, we use the document.querySelectorAll method to select all input elements on the page. This method returns a NodeList containing all the input elements.

We iterate through each input element using the forEach method of the NodeList. Inside the loop, we retrieve the ID and value of each input element using the id and value properties, respectively. We then store the value in the inputValues object using the ID as the key.

Finally, we log the inputValues object to the console, but you can modify this part to perform any desired operations with the collected input values.

When you open the HTML file in a browser and enter values in the input fields, clicking the “Submit” button will trigger the collectInputs function. This function will collect the values of all input fields and store them in the inputValues object, which is then logged to the console.

Please note that this example assumes that all input elements on the page are of type “text.” If you have different types of input fields (e.g., checkboxes, radio buttons, etc.), you might need to adjust the code accordingly.