0

I want to create a list of all the names of a form's elements. however with the following code I got the error: "inputs.map is not a function"

I am aware the inputs is not an array, however I am not sure about how to get a this .map to function ?

function process(form) {
  console.dir(form)
  var inputs = form.elements
  for (let i = 0; i < inputs.length; i++) {
    console.log(i+':'+inputs[i].name+': '+inputs[i].value);
  }
  let names = inputs.map( e => e.name )

  console.log(names)
  
}
<form name=form1 method=none>
firstname: <input name=lastn value="a" type=text>
<br>lastname: <input name=firstn value="b" type=text>
<br>zipcode: <input name=zip value="c" type=text>
<br>ip: <input name=ip value="127.0.0.1" type=text disabled>
<br><input onclick="process(this.parentNode)" name=button type=button value="register">
</form>

btw to run the code you have to click the "register" button (as it is an "onclick" call)

2 Answers2

3

HTMLFormElement.elements is an HTMLFormControlsCollection, which is an array like object, and not an actual array. Convert it to an array using Array.from():

function process(form) {
  var inputs = Array.from(form.elements)

  const names = inputs.map(e => e.name)

  console.log(names)
}
<form name=form1 method=none>
  firstname: <input name=lastn value="a" type=text>
  <br>lastname: <input name=firstn value="b" type=text>
  <br>zipcode: <input name=zip value="c" type=text>
  <br>ip: <input name=ip value="127.0.0.1" type=text disabled>
  <br><input onclick="process(this.parentNode)" name=button type=button value="register">
</form>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

I found the way to solve my own problem, so I thought it might be useful to share with the community what I just learned

Object.values(inputs) does the trick !

function process(form) {
  var inputs = form.elements
  console.log('inputs: ',inputs);
  let list = Object.values(inputs)
  console.log('list: ',list)
  let names = list.map( e => e.name )
  alert('names: ['+names.toString()+"]\nvoila !")
}
<form name=form1 method=none>
firstname: <input name=lastn value="a" type=text>
<br>lastname: <input name=firstn value="b" type=text>
<br>zipcode: <input name=zip value="c" type=text>
<br>ip: <input name=ip value="127.0.0.1" type=text disabled>
<br><input onclick="process(this.parentNode)" name=button type=button value="register">
</form>