JavaScript temp variable
Hi this is the situation
var seat_sel = document.getElementById('cmb_num_seat').value;
var cashp = document.getElementById('hdn_price').value;
var CHILD_PRICE = '5'
if(seat_sel > 0){
CHILD_PRICE = CHILD_SEAT_PRICE * seat_selected;
}else{
CHILD_PRICE = CHILD_SEAT_PRICE * seat_selected;
}
document.getElementById('disp_2_div').innerHTML = formatCurrency(parseInt(cashp)+parseInt(CHILD_PRICE));
document.getElementById('hdn_price').value = formatCurrency(parseInt(cashp)+parseInt(CHILD_PRICE))
For example...
i have cashp=20
,
When user select the cmb_num_seat(DROP DOWN)
, Then Price will be increase That is
20+(5*3)=20+15=45
Assume i selected 3 in the dropdown...
But in some situation , Calculation goes wrong...
Lik开发者_如何学JAVAe select 3 , and then select 4 and then select 2 and then selecting 1 ,
In this situation old value hdn_price is over riding ...bcoz of ADDITION ...
Is there any way ...maintain first value in some variable and then doing the calculation...
I don't know exactly what the problem is with your code or what you think it is, put I see several potential problems:
- You mix data types wildly.
- You use a variable that seems not to be initialised (seat_selected).
Also, you have an if
statement that does exactly the same thing in both cases, and you initialise CHILD_PRICE
to a string, but the following code always replaces it with a numeric value.
If you are going to do calculations on numbers, parse the values before doing the calculations. Don't be afraid to use a few more variables for intermediate values, it doesn't have any noticable effect performance, and it makes the code more readable.
If you want to keep the start price, you should read the value from the hidden field once when the page loads:
var price = parseInt(document.getElementById('hdn_price').value);
Then you use the variable in the update code:
var seats = parseInt(document.getElementById('cmb_num_seat').value);
var childPrice = CHILD_SEAT_PRICE * seats;
var display = formatCurrency(cash + childPrice);
document.getElementById('disp_2_div').innerHTML = display;
document.getElementById('hdn_price').value = display;
精彩评论