Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript函数不工作_Javascript_Jquery - Fatal编程技术网

Javascript函数不工作

Javascript函数不工作,javascript,jquery,Javascript,Jquery,我正在尝试使用下面的函数来查找表单字段中的值,其循环的原因是表单会动态更改,这意味着字段的ID中可能存在间隙 Java脚本函数是 function totalProductPrice() { var maxid = document.getElementById("field_id").value; var i = 0; var totalprice = 0; while (i<=maxid) {

我正在尝试使用下面的函数来查找表单字段中的值,其循环的原因是表单会动态更改,这意味着字段的ID中可能存在间隙

Java脚本函数是

function totalProductPrice() {
        var maxid = document.getElementById("field_id").value;
        var i = 0;
        var totalprice = 0;

        while (i<=maxid)
            {
                totalprice += document.getElementById("QuoteItem" + i + "price").value;
                i++;
            }

        document.getElementById("QuoteTotalcost").value = totalprice;
    }
当我更改此字段的值时,它应该将所有字段相加,然后将其插入名为QUoteTotalcost的字段中,但当我尝试时,它什么也不做,在firebug的控制台中输出

element.dispatchEvent is not a function
[Break on this error] element.dispatchEvent(event);
prototype.js (line 4619)
document.getElementById("QuoteItem" + i + "price") is null
[Break on this error] totalprice += document.getElementById("QuoteItem" + i + "price").value; 

这样做是因为您试图读取空对象上的属性。您需要检查对象是否存在

while (i <= maxid) {
  var item = document.getElementById("QuoteItem" + i + "price");
  if (item != null) {
    totalprice += parseFloat(item.value);
  }
}
编辑2:表单字段值是字符串。如果对它们使用
+
,则这是一个字符串串联。我修改了上面的调用,以将任何值转换为数字。您可能需要使用以下方法将其转换为固定的小数位数:


从firebug错误来看,id似乎无效。您确定有ID为“QuoteItem1price”、“QuoteItem2price”等的元素吗。。你检查过区分大小写吗?是的,我检查了一遍又一遍,只是为了确保我没有发疯。id确实会根据创建和删除的内容而变化-即在某些情况下,第一个有效的id将引用EM4价格,因此它应该能够跳过前3个,而不会出现任何问题。我认为它解决了问题错误和它现在被传递到totalprice字段,但是除了将这些值加在一起,它只是将其附加到上一个字段上,有什么想法吗?谢谢你-很抱歉,我没有意识到PHP的不同之处,它为你解决了所有问题,干杯:D
while (i <= maxid) {
  var item = document.getElementById("QuoteItem" + i + "price");
  if (item != null) {
    totalprice += parseFloat(item.value);
  }
}
<input type="text" class="quote-item-price">
var items = document.getElementByTagName("input");
for (var i=0; i<items.length; i++) {
  if (items[i].className == "quote-item-price") {
    totalprice += parseFloat(items[i].value);
  }
}
var totalprice = 0;
$("input.quote-item-price").each(function() {
  totalprice += parseFloat($(this).val());
  // or
  totalprice += parseFloat(this.value);
});
totalprice = totalprice.toFixed(2);