如何在提交时获取表单值?

时间:2019-09-05 09:22:00

标签: javascript html

<form name="dome" onsubmit="return validateForm()" method="get">
    <input type="text" name="comment[]" value="comment1"/>
    <input type="text" name="comment[]" value="comment2"/>
    <input type="text" name="comment[]" value="comment3"/>
    <input type="text" name="comment[]" value="comment4"/>
</form>

我知道我可以发送多个具有相同名称的输入,并通过在输入名称中添加空方括号来将它们保存到数组中,就像代码中一样。

现在,我想获取JavaScript中的所有值,以便在提交时进行验证。
我已经尝试过了,但是没有用。

var comment_list = document.forms["dome"]["comment[]"].value;

3 个答案:

答案 0 :(得分:0)

您必须遍历数组,并检查是否有任何元素为空,如下所示。

var inps = document.getElementsByName('comment[]');
for (var i = 0; i <inps.length; i++) {
  var inp=inps[i];
  if(!inp.value){
    alert('Enter value for box ' + (i +  1));
  }
}
 <form name="dome" onsubmit="return validateForm()" method="get">
      <input type="text" name="comment[]" value="comment1"/>
      <input type="text" name="comment[]" value="comment2"/>
      <input type="text" name="comment[]" value=""/>
      <input type="text" name="comment[]" value="comment4"/>
    </form>

答案 1 :(得分:0)

返回comment_listnodeList。您必须对其进行迭代。例如:

var comments = [];

var comment_list = document.forms["dome"]["comment[]"].forEach(function(el) {
  comments.push(el.value);
});

console.log(comments);
<form name="dome" onsubmit="return validateForm()" method="get">
  <input type="text" name="comment[]" value="comment1"/>
  <input type="text" name="comment[]" value="comment2"/>
  <input type="text" name="comment[]" value="comment3"/>
  <input type="text" name="comment[]" value="comment4"/>
</form>

答案 2 :(得分:0)

您可以将this传递给validateForm,这将包含表单的内容。然后,您可以将其转换为数组,并从表单中映射值。或者,您可以映射document.forms["dome"]["comment[]"]来获取值。

请参阅以下演示(我添加了提交按钮,您必须打开浏览器控制台才能看到结果,因为提交清除了输出-formcontent的最后一个元素是该按钮)

function validateForm(formcontent) {
  let arr = Array.from(formcontent).map(({value}) => ({value}));
  console.log("formcontent:",JSON.stringify(arr))

  let alternative = Array.from(document.forms["dome"]["comment[]"]).map(({value})=>({value}));
  console.log('document.forms["dome"]["comment[]"]:', JSON.stringify(alternative));
}
<form name="dome" onsubmit="validateForm(this)" method="get">
  <input type="text" name="comment[]" value="comment1" />
  <input type="text" name="comment[]" value="comment2" />
  <input type="text" name="comment[]" value="comment3" />
  <input type="text" name="comment[]" value="comment4" />
  <button type="submit">submit</button>
</form>