How to get hidden field array values

I have multiple hidden fields of the form
<input type=“hidden” class=“mail-contacts” name=“to” value=“abc1”>
<input type=“hidden” class=“mail-contacts” name=“to” value=“abc2”>
<input type=“hidden” class=“mail-contacts” name=“to” value=“abc3”>

Number of hidden fields can be different for different cases. How can i get the values of these hidden fields ? As this is an array so can’t get it with
document.getElementById(‘’)
I need to get the values of these hidden fields and then pass it as query parameter. Please help me out how can i do this. Thanks.

Hi there,

Why is it an array?
Have I missed something?

One way to get the values of multiple hidden fields within a form would be to select all of the input elements and loop through them:

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Get hidden input values</title>
  </head>
  
  <body>
    <form id="myForm" method="post">
      <input type="hidden" class="mail-contacts" name="to[]" value="abc1">
      <input type="hidden" class="mail-contacts" name="to[]" value="abc2">
      <input type="hidden" class="mail-contacts" name="to[]" value="abc3">
      
      <input type="submit" value="Submit" />
    </form>
    
    <script>
      var form = document.getElementById("myForm"),
          inputs = form.getElementsByTagName("input"),
          arr = [];
          
      for(var i=0, len=inputs.length; i<len; i++){
        if(inputs[i].type === "hidden"){
          arr.push(inputs[i].value);
        }
      }
      
      console.log(arr);
    </script>
  </body>
</html>

Thanks for the response.
I want to get values of all hidden fields with name “to” in one javascript array and pass it in query string, that is the reason i am putting array for hidden fields.
Couple of things i need help abt your code:

  1. How can i get only those hidden field values whose name is “to”
  2. Is it possible to send array “arr” as query parameter ?
if(inputs[i].type === "hidden" && inputs[i].name === "to[]"){
  ...
}

Although, I would hazard a guess that using the name attribute in this way is not the best method of to achieving what you want.

Depends what you are doing with your form.
If you are making an AJAX request, then why not - just pass it as a parameter in the normal way:

xmlhttp.open("GET","ajax.php?arr="+arr,true);
xmlhttp.send();

Otherwise, all of the values will be submitted to your form anyway.
It would make much more sense to process them on the server.