首页 > 解决方案 > 如何在表单元素上使用 map 方法

问题描述

我想创建一个表单元素的所有名称的列表。但是使用以下代码我得到了错误:“inputs.map 不是函数”

我知道这inputs不是一个数组,但是我不确定如何让 this.map起作用?

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>

顺便说一句,要运行代码,您必须单击“注册”按钮(因为它是“onclick”调用)

标签: javascriptarraysformsdictionaryelement

解决方案


HTMLFormElement.elements是一个HTMLFormControlsCollection,它是一个类似对象的数组,而不是一个实际的数组。使用以下方法将其转换为数组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>


推荐阅读