为什么onchange和onblur有时只能工作?

时间:2017-03-02 01:02:09

标签: onchange onblur

我的表单包含少量字段,用户可以在其中添加类似

的值
<input name='extracost' type='text' size='25' id='extracost' value='$extracost' onChange='calculate();' >

问题在于onBlur或onChange只是&#39;似乎&#39;工作一次。如果元素extracost以0或null开头,例如,如果我将其在窗体上更改为50,则该函数似乎正常工作并且总计增加50但是如果我将其设置为0,则它​​什么都不做。如果我再次将其设置为-50,它将随后工作。

如果我将提取时间设置为50,然后是60,然后是70,则总数会增加180。

这是相关的javascript

var subtotal = document.getElementById("subtotal").value;
var extracost = document.getElementById("extracost").value;
var total = Number(subtotal) + Number(extracost); 
document.getElementById("total").value = total;

我已经在这里阅读了许多类似问题的线程,但没有一个解决方案有效。

2 个答案:

答案 0 :(得分:0)

首先,您的源代码中没有onBlur事件。

此外,尝试解析文本框值:

var subtotal = parseInt(document.getElementById("subtotal").value, 10);
var extracost = parseInt(document.getElementById("extracost").value, 10);
var total = (subtotal) + (extracost); 
document.getElementById("total").value = total;

我认为你在Chrome中遇到了这个问题。最后,onChange和onBlur仅在光标离开文本框时才起作用。

答案 1 :(得分:0)

通过消除此

找到了我的问题的解决方案
var subtotal = parseInt(document.getElementById("subtotal").value, 10);

并收集用于计算小计的所有单个表单变量,并简单地重新计算它。

相关问题