frontend
alwaisy
2 min read

How to store HTML form value in an array

To get input from an HTML input element and store it in an array in JavaScript, you can use the value property of the input element and the push() method of the array.

Here's an example of how you can do this:

index.html
<!-- HTML code --> <form id="form"> <input type="text" id="input1" /> <input type="text" id="input2" /> <input type="text" id="input3" /> <button type="button" onclick="storeInput()">Store Input</button> </form>
  • The first step is to get the values of the input elements with the ids input1, input2, and input3 on the button clicked
  • To store the values in the inputArray array. Create an array named inputArray
  • You can add as many input elements as you need, and modify the code to store the values in the array as needed.
script.js
function storeInput() { // Initialize an empty array const inputArray = []; // Get the input elements const input1 = document.getElementById("input1"); const input2 = document.getElementById("input2"); const input3 = document.getElementById("input3"); // Get the values of the input elements const value1 = input1.value; const value2 = input2.value; const value3 = input3.value; // Add the values to the array inputArray.push(value1, value2, value3); // Print the array to the console console.log(inputArray); }

Note that this code assumes that the input elements are inside a form element with the form id. You can modify the code to use a different form element or to get the input elements in a different way.