Tarik Seyceri Tarik Seyceri - 3 months ago 15
HTML Question

HTML Input Array: How to get html input array values with javascript

I have this code which works fine!:



<script>
function get(userfirstname, userlastname){
alert(userfirstname);

return false;
}
</script>

<form action="" method="POST">
<input type="text" name="userfirstname">
<input type="text" name="userlastname">
<input type="submit" onclick="return get(userfirstname.value, userlastname.value);">
</form>





i am trying to catch the input values with an array like this:



<script>
function get(user){
alert(user["firstname"].value);

return false;
}
</script>

<form action="" method="POST">
<input type="text" name="user[firstname]">
<input type="text" name="user[lastname]">
<input type="submit" onclick="return get(user);">
</form>





i tried so many different scenarios, no point :(

Any hint would be appreciated.

Answer

You could simply target the form element inside your onclick handler, query all input elements to iterate over them and build the array you are looking for.

Here is an example of what you could do to build an array of objects holding each input elements name and value, excluding disabled once and the submit element.

function get(evt){
  var fields = [];
  event.target.parentElement
  .querySelectorAll('input:not([disabled]):not([type="submit"])').forEach(function(e) {
    fields.push({name: e.name, value: e.value}); 
  })
  console.log(fields);
  return false;
}
<form>
  <input type="text" name="firstname" placeholder="Name"><br>
  <input type="text" name="lastname" placeholder="Surename"><br>
  <input type="text" name="foo" value="foo will be excluded" disabled><br>
  <input type="submit" onclick="return get();">
</form>

Comments