【问题标题】:Adding multiple text boxes in html using javascript使用javascript在html中添加多个文本框
【发布时间】:2014-07-17 21:36:34
【问题描述】:

我正在尝试添加多个文本框整数值和要存储在另一个文本框中的总和。

<script>
function updatesum(){
cash =  parseInt(document.rent_form.cash.value,10);
card = parseInt(document.rent_form.card.value,10);
online = parseInt(document.rent_form.online.value,10);
deduction = parseInt(document.rent_form.deduction.value,10);
actAmount    = parseInt(document.rent_form.actAmount.value,10);
tot = actAmount - (cash+card+online+deduction);
document.rent_form.bal.value = tot;
}
</script>

我在 name="bal" 的文本框中显示 NaN 值

<form class="form-horizontal" name="rent_form" id="rent_form" action="php/tenantTable.php" 
method="POST">
<input type="text" id="act_rent_amount" name="actAmount" class="input-xlarge" placeholder="" 
value="<?php echo ($row['rent_amount']); ?>" style="visibility: hidden">
<input type="text" name="cash" onChange="updatesum()" value="0">
<input type="text" name="card" onChange="updatesum()" value="0">
<input type="text" name="online" onChange="updatesum()" value="0">
<input type="text" name="deduction" onChange="updatesum()" value="0">
<input type="text" id="bal" name="bal">

这里是a link

【问题讨论】:

  • 老实说,我没有看到任何带有 name="bal" 的输入文本框。它在您发布的代码中的什么位置?
  • 刚刚添加,脚本在head部分

标签: javascript html forms textbox


【解决方案1】:

如果你想读取一个输入的值,你需要使用document.getElementById("inputid")。所以而不是

cash =  parseInt(document.rent_form.cash.value,10);

你需要使用

cash =  parseInt(document.getElementById("cash").value,10);

您还需要为所有输入字段提供一个 ID。如果要使用名称,则需要使用getElementsByName()[0],它返回具有该名称的第一个元素(但请使用ID,它更准确,更易于阅读)。

但是,因为您有 5 次相同的逻辑序列,所以我会稍有不同并将其包装到一个函数中:

function ParseElementValue(elementName){
    return parseInt(document.getElementById(elementName).value,10);
}

然后这样称呼它:

cash = ParseElementValue("cash");
card = ParseElementValue("card");

【讨论】:

    猜你喜欢
    • 2019-11-26
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多