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;
-
the id seems invalid from the firebug errors. are you sure you have elements with ids as "QuoteItem1price", "QuoteItem2price", etc.. and did you check the case sensitivity?Anurag– Anurag2010年01月29日 11:33:39 +00:00Commented Jan 29, 2010 at 11:33
-
Yeah i checked it over and over just ot make sure i wasnt going crazy..the id does vary according to what has been created and deleted - ie in some cases the first valid one will be QuoteItem4price so it should be able to skip through those first 3 without any issues i would imaginekwhohasamullet– kwhohasamullet2010年01月29日 11:37:59 +00:00Commented Jan 29, 2010 at 11:37
1 Answer 1
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);