r2 and r3 on load there were no values for it to find, causing the NaN.
here are my changes:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
Distance<input type="text" id="distance" value="1" />
<span class="dresult"></span> first km is 30k USD, the
next kms is 1k USD each<br />
Weight<input type="text" id="weight" value="0" />
<span class="wresult"></span> no extra fee for good
under 5kg<br />
urgent<input type="checkbox" id="priority" />
<span class="presult"></span> urgent good 5k USD
extra<br />
<div>total to pay: <span class="grandtotal"></span></div>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('input[type="text"]').bind("keyup",calculate);
calculate();
function calculate() {
var firstkm = 30000, nextkm = 1000;
var distance = $('#distance').val();
if(distance > 1){$('.dresult').text(firstkm + nextkm*(distance-1) +
'USD');}
else {$('.dresult').text(firstkm + 'USD');}
var weight = $('#weight').val(), perkg = 5000;
if(weight > 5) {$('.wresult').text((weight-5)*5000 + 'USD');}
else {$('.wresult').text(0 + 'USD');}
total();
}
$('.presult').text('0 USD');
total();
$('#priority').change(function(){
if ($(this).attr('checked') == true)
{
$('.presult').text('5000 USD');
}
else
{
$('.presult').text('0 USD');
}
total();
});
function total() {
var r1 = parseInt($('.dresult').text()),
r2 = parseInt($('.wresult').text()),
r3 = parseInt($('.presult').text());
$('.grandtotal').text(r1 + r2 + r3);
};
});
</script>
</body>
</html>
Shawn wrote:
>
> further to that, you can do
>
> var distance = parseInt($("#distance".val(), 10);
>
> Using the radix (the second parameter - 10 in this case), forces the
> specific conversion you'd like. When dealing with dates at least,
> leaving out the radix can sometimes result in abnormal behavior that
> is VERY hard to troubleshoot.
>
> Oh, if the number is not an integer, use parseFloat() instead of
> parseInt(). (er, sry if this is TOOO basic.. :) )
>
> Shawn
>
> Giovanni Battista Lenoci wrote:
>>
>> runrunforest ha scritto:
>>> Hi, I'm making a calculator for freight customer
>>>
>>> It seems I'm on the right path. But there is two bugs i need help.
>>>
>>> The TOTAL TO PAY value always seem to appear as NaN at first instead
>>> of default 30000.
>>>
>>> And the function of TOTAL TO PAY only work after checkbox is checkd, I
>>> need it work regarding to changing of input value not just checkbox.
>>>
>>
>> I didn't chek all of your code, but remember:
>>
>> $('#distance').val();
>>
>> returns a string, not an int.
>>
>> Bye
>>
No comments:
Post a Comment