Open In App

How to get values from html input array using JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

This problem can be solved by using input tags having the same “name” attribute value that can group multiple values stored under one name which could later be accessed by using that name.

Syntax:

let input = document.getElementsByName('array[]');

Using Document.getElementsByName() method

It returns all the values stored under a particular name thus making the input variable an array indexed from 0 to the number of inputs.

The method document.getElementById().innerHTML is used to change the inner HTML of the selected Id. So in this way, we can access the input values and convert them into the array and access it as you like.

Example: In this example, the HTML document contains a form with an array of text input elements named “array[]”. The JavaScript function Geeks() retrieves the values from these input elements, iterates through them, and dynamically constructs a string displaying the respective values.

html




<!DOCTYPE html>
<html lang="en" dir="ltr">
 
<head>
    <meta charset="utf-8">
    <title>
        How to get values from html input
        array using JavaScript ?
    </title>
</head>
 
<body style="text-align: center;">
 
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
 
    <h3 id="po">Input Array Elements</h3>
    <form class="" action="index.html" method="post">
        <input type="text" name="array[]" value="" /><br>
        <input type="text" name="array[]" value="" /><br>
        <input type="text" name="array[]" value="" /><br>
        <input type="text" name="array[]" value="" /><br>
        <input type="text" name="array[]" value="" /><br>
        <button type="button" name="button" onclick="Geeks()">
            Submit
        </button>
    </form>
    <br>
 
    <p id="par"></p>
 
    <script type="text/javascript">
        let k = "The respective values are :";
        function Geeks() {
            let input = document.getElementsByName('array[]');
 
            for (let i = 0; i < input.length; i++) {
                let a = input[i];
                k = k + "array[" + i + "].value= "
                    + a.value + " ";
            }
 
            document.getElementById("par").innerHTML = k;
            document.getElementById("po").innerHTML = "Output";
        }
    </script>
</body>
 
</html>


Output:

newwwwwwwwwwwwww

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Last Updated : 14 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads