Javascript function not working

I am trying to use the following function to search for values ​​in form fields. The reason its loops are because the form changes dynamically, which means there may be spaces in the field identifier

Java script function

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

and then on one of the input fields i

onchange='totalProductPrice();'

When I change the value of this field, it must compose all the fields and then insert them into the QUOTTotalcost field, but when I try it, nothing happens. In the console firebug gives

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; 
+3
source share
1 answer

This is because you are trying to read a property on a null object. You need to check if the object exists.

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);
  }
}

, , , ..

: jQuery. jQuery .

var totalprice = 0;
$("input.quote-item-price").each(function() {
  totalprice += parseFloat($(this).val());
  // or
  totalprice += parseFloat(this.value);
});

2: . + , . , parseFloat(), . , toFixed():

totalprice = totalprice.toFixed(2);
+4

Source: https://habr.com/ru/post/1730523/


All Articles