For different quantities, the unit price changes. I have a quantity dropdown box, a span for unit price, subtotal and total.
I want to make it so that when the dropdown box is changed, the unit price will updated, then subtotal will be updated, then the total price will be updated. So far I am using:
$('#quantity').change( function() {
var pricetable = {
"1": "368",
"3": "338",
"6": "298"
}
$('#unitprice').text(pricetable.$('#quantity').val());
$('#subtotal').text($('#unitprice').val() * $('#quantity').val());
subtotalsum();
});
I know that pricetable.$('#quantity').val() is wrong, but don’t know how to use $('#quantity').val() to lookup the JSON price table.
Thanks in advance
Like this:
What you have there is a JavaScript object, not a JSON table. (JSON is a textual notation used for data exchange; this is source code. JSON is a subset of what you’re using there, which is JavaScript object initializer syntax.)
In JavaScript, you can refer to a property on an object in one of two ways:
Using dotted notation and a literal property name, e.g.,
obj.foo.Using bracketed notation and a string property name, e.g.,
obj["foo"]. (If you use something other than a string, it’s converted to a string before being used.)In the latter case, the string can be the result of any expression, it doesn’t have to be a literal.
So in the line of code above, we get the current value of the
quantitybox, which will be a string like"1","2", etc., and we use that to look up the relevant property in thepricetableobject. Finally, we use that to set the text of theunitpriceelement.