繁体   English   中英

在JavaScript中添加多个HTML表单输入值

[英]Adding multiple HTML form input values in JavaScript

为什么我不能将三个数字加在一起,我感到困惑。 这是我的HTML:

<div><label>Sales Price: </label>
    <input type="number" name="sales_price" value="3">
</div>
<div><label>Incentives: </label>
    <input type="number" name="incentives" value="2">
</div>    
<div><label>Acquisition Fee: </label>
    <input type="number" name="acq_fee" value="1">

这是我的JavaScript:

var salesPrice = document.getElementsByName("sales_price")[0];
var incentives = document.getElementsByName("incentives")[0];
var acqFee = document.getElementsByName("acq_fee")[0];

var netCapCost = salesPrice.value - incentives.value + acqFee.value;

我想做一个简单的计算:(3-2 + 1)=2。但是, netCapCost返回11,这是(3-2)和1的结果的并置。我做错了什么? 提前谢谢了!

您需要使用parseInt()将这些值转换为数字,否则+运算符将被解释为字符串连接。 你在做

var netCapCost = salesPrice.value - incentives.value + acqFee.value;

哪一个

var netCapCost = "3" - "2" + "1"

"3"-"2"将返回1,这是您想要的,但是1 + "1"将被连接为"11"因为右操作数是一个字符串。 所以数字+字符串->串联

您正在执行字符串连接,所有从输入值获取的值都是字符串,

首先计算salesPrice.value - incentives.value .value是正确的,因为-号将promotions.value转换为数字

正确的方法是

var netCapCost = parseInt(salesPrice.value, 10) - parseInt(incentives.value, 10) + parseInt(acqFee.value, 10);

最好使用数学库在javascript中进行计算,因为迟早会遇到类似0.3 - 0.2 = 0.09999999

 var salesPrice; var incentives; var acqFee; var npc; function calculate(e) { var netCapCost = (parseFloat(salesPrice.value) - parseFloat(incentives.value) + parseFloat(acqFee.value)).toPrecision(3); npc.value = netCapCost; } window.onload = function (){ salesPrice = document.getElementsByName("sales_price")[0]; incentives = document.getElementsByName("incentives")[0]; acqFee = document.getElementsByName("acq_fee")[0]; npc = document.getElementsByName("npc")[0]; salesPrice.onchange = calculate; calculate(); }; 

您的问题是文本字段的值始终为STRING类型。 减去时将强制转换为FLOAT类型。 然后加号操作与串联操作共享一个运算符。 因此,当您添加两个字符串时,它会串联在一起,而不是转换为FLOAT或INT。 因此,基本上,您有将“ 2”-“ 1”转换为2-1的原因,因为不能减去字符串,这会给您(1),那么您就有了(1)+“ 1”,它们会串联起来而不是加起来,因为您有字符串。 当期望来自用户输入的数字数据时,请始终使用parseFloat或parseInt,因为最初提交时它将始终是字符串。

我认为这里的困惑是HTML 5引入了输入类型号,但是javascript引擎并未引入对读取此类特定字段的支持。 我们最终使用了传统的读取输入字段值的传统方法,该方法将所有内容默认为字符串。

使用数字类型字段的唯一好处是,您不必担心未输入数字的异常/错误情况。

建议使用parseInt函数的其他答案是一种方法,除非您有很多介绍jQuery之类的JavaScript框架并使用更复杂的方法来阅读它的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM