簡體   English   中英

使用JavaScript在HTML中添加多個文本框

[英]Adding multiple text boxes in html using javascript

我試圖添加多個文本框的整數值和總和要存儲在另一個文本框中。

<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>

我正在顯示名稱為“ 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">

這是一個鏈接

如果要讀取輸入的值,則需要使用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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM