Javascript function not working
Im trying to use the below function to find values in form fields, The reason its loops is because the form changes dynamically which means there could be gaps in the ID of the field
Java script function is
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 have
onchange='totalProductPrice();开发者_开发知识库'
When i change the value of this field it should add up all the fields and then insert it into the field called QUoteTotalcost but when i try it does nothing, In the console of firebug it outputs
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;
It does that because you're 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);
}
}
That's a somewhat crude way of adding up totals though. Its usually better to use classes for this kind of thing:
<input type="text" class="quote-item-price">
with:
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);
}
}
That way you don't have to mess around with IDs to make sure they're unique, etc.
Edit: You've tagged your question with jQuery. With jQuery it's much much simpler.
var totalprice = 0;
$("input.quote-item-price").each(function() {
totalprice += parseFloat($(this).val());
// or
totalprice += parseFloat(this.value);
});
Edit 2: form field values are strings. If you use +
with them it is a string concatenation. I've modified the above to call parseFloat()
to convert any values to numbers. You may need to convert that to a fixed number of decimal places using toFixed()
:
totalprice = totalprice.toFixed(2);
精彩评论