【问题标题】:Sum the values of the inputs of a specific form and display the result对特定表单的输入值求和并显示结果
【发布时间】:2017-10-28 17:05:30
【问题描述】:

我的页面由多个表单组成,其中包含多个名为“values[]”的输入。 在其中一种形式中修改这些输入时,我想对这些值求和并将结果显示在另一个名为“total”的相同形式的输入中。

我的 html 代码如下所示:

<form action="index.php" method="post" id="form_1"> 
    <input type="text" name="values[]" id="value_1_1" onkeyup="sum_values(this)" />
    <input type="text" name="values[]" id="value_1_2" onkeyup="sum_values(this)" />
    [... More inputs with the name "values[]" ]
    <input type="text" name="total" disabled>
</form>

<form action="index.php" method="post" id="form_2">
    <input type="text" name="values[]" id="value_2_1" onkeyup="sum_values(this)" />
    <input type="text" name="values[]" id="value_2_2" onkeyup="sum_values(this)" />
    [... More inputs with the name "values[]" ]
    <input type="text" name="total" disabled>
</form>

我的 javascript 是:

<script type="text/javascript">
function sum_values(x){
    var arr = document.getElementById(x.form.id).elements['values[]'];
    var tot=0;
    for(var i=0;i<arr.length;i++)
    {
        if(parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
    }
    document.getElementById(x.form.id).elements['total'].value = tot;   
}
</script>

我很高兴终于看到第一个表单工作了,但后来我发现第二个表单不行......

你能帮我理解为什么吗? 我是 javascript 的初学者,我试图安排一些我找到的代码。 非常感谢

【问题讨论】:

  • 不应该是var arr = document.getElementById(x.form.id).value
  • 如果我是正确的,“x.form.id”给出了整个表单的 id。您引用的行应该在此表单(而不是整个表单)中获取名称为“values []”的输入。
  • 然后使用 x.id 代替 x.form.id ,这肯定会工作

标签: javascript forms input sum


【解决方案1】:

如果您想获取特定表单中的所有元素,可以使用类似于以下的代码来实现。除了最终结果输入选择器之外,其余代码应该可以正常工作。

var formId = 'form1';
var arr = document.querySelectorAll('#' + formId + ' [name="values[]"]');

var tot=0;
for(var i=0; i<arr.length; i++) {
  if(parseInt(arr[i].value))
    tot += parseInt(arr[i].value);
}
document.querySelector('#' + formId + ' [name="total"]').value = tot;
<form id="form1">
  <input type="text" name="values[]" value="5" />
  <input type="text" name="values[]" value="1" />
  <input type="text" name="values[]" value="6" />
  <input type="text" name="values[]" value="8" />
  <input type="text" name="values[]" value="2" />
  <input type="text" name="values[]" value="0" />
  <input type="text" name="values[]" value="1" />
  <input type="text" name="values[]" value="3" />
  <input type="text" name="total" disabled>
</form>

【讨论】:

  • 太完美了,我只需要用 x.form.id 替换 'form1'。我不知道这种访问输入的方式。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
相关资源
最近更新 更多