Title: Calculate the quantity on layer based on price
Tags: javascript;php;jquery;html
Question: I want to calculate the layer cost of making a cake based on option from the customer.
1 layer cost 320.00 ( set price for 1 layer already)
Additional layer cost 100
In html i have this:
<select id="layer" name="layer" onchange="updateTotal()" &gt;
<?php   for( $i=1; $i<100; $i++ ) {
echo "<option value=$i&gt; $i </option&gt;\n"; }
?&gt;
</select&gt;
In my javascript I have this:
function updateTotal(){
var optionPrice = 0;
function cakeLayerPrice(){
document.getElementById('layer');
optionPrice += 100;}
cakeLayerPrice();
var totalPrice = optionPrice;
document.getElementById('totalPrice').innerHTML = "$ " + totalPrice;
Apparently the amount won't display if I choose even 1 layer, in my function cakeLayerPrice(), what is the right solution?
e.g. it will display
if I choose
1 layer = 320.00
2 layers = 420.00 (+100)
3 layers = 520.00 (+100) and so on.

Here is the accepted answer: Each time you're calling updateTotal() you're resetting optionPrice to 0.
Instead you should get from layer select box the layer number and multiply it to 100.
function updateTotal(){
var layers = document.getElementById('layer');
var totalPrice = parseInst(layers.value, 10) * 100;
document.getElementById('totalPrice').innerHTML = "$ " + totalPrice;
If nothing is selected, or you did't set a default selected, you could get a -1 value.
In this case, just update the code to handle the negative values:
function updateTotal(){
var layers = document.getElementById('layer');
var totalPrice = parseInst(layers.value, 10) * 100;
if (totalPrice &gt; 0) {
document.getElementById('totalPrice').innerHTML = "$ " + totalPrice;
This example, avoids even the case your price is 0.
If you have this possibility, just change the code as needed.
Comment for this answer: alright i'll try this out. I have lots of functions which are pretty similar. My main function is the updateTotal() where I'll add these functions in the end which works perfectly fine. I just got confused when it comes to layer as well this applies to quantity. Thank you.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:10/30/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><php><jquery><html>', 'Title': 'Calculate the quantity on layer based on price', 'ViewCount': 60, 'id': 40326811, 'user_AboutMe': '<p>New to the world of codings, doing my best to adapt myself despite the lack of resources in our school. I have a part-time job and would like to learn something new and fun which in the future I can use it.</p>\n', 'user_AccountId': 9544002.0, 'user_DisplayName': 'Poofbrayy', 'user_Reputation': 21.0, 'user_Views': 29.0, 'user_id': 7090857.0}}