> 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.
Consider something like;
<script type="text/javascript">
var updater = (function() {
var distanceEl,
weightEl,
wresultEl,
priorityEl,
presultEl,
grandtotalEl;
var intRe = /\D/;
var firstK = 30000;
var nextK = 1000;
// Get the value of el
function getValue(el) {
var val = el.value.replace(/ /g,'');
return !intRe.test(val)? Number(val) : NaN;
}
// Return reference to element using id
function getEl(id) {
return document.getElementById(id);
}
return {
setup: function() {
distanceEl = getEl('distance');
dresultEl = getEl('dresult');
weightEl = getEl('weight');
wresultEl = getEl('wresult');
priorityEl = getEl('priority');
presultEl = getEl('presult');
grandtotalEl = getEl('grandtotal');
updateEl = getEl('updateCell');
resetEl = getEl('resetButton');
distanceEl.onchange = updater.run;
weightEl.onchange = updater.run;
wresultEl.onchange = updater.run;
priorityEl.onchange = updater.run;
distanceEl.onchange = updater.run;
resetEl.onclick = updater.runLate;
if (updateEl) {
var el = document.createElement('input');
el.type = 'button';
el.value = 'Update total';
el.onclick = updater.run;
updateEl.appendChild(el);
}
updater.run();
},
run: function() {
var d = getValue(distanceEl);
var w = getValue(weightEl);
var dCost = 0;
var wCost = 0;
var pCost = 0;
// Check for errors, don't continue if found
if ((!d && d != 0) || d < 0) {
alert('Invalid distance, must be an integer.');
return;
} else if ((!w && w != 0 ) || w < 0) {
alert('Invalid weight, must be an integer.');
return;
}
// Calculate cost for distance
if (d > 0) {
dCost = 30000;
--d;
}
dCost += d * 1000;
dresultEl.innerHTML = 'USD' + dCost;
// Calculate cost
if (w > 5) {
wCost = (w - 5) * 5000;
}
wresultEl.innerHTML = 'USD' + wCost;
// Add extra if priority
if (priorityEl.checked) {
pCost = 5000;
}
presultEl.innerHTML = 'USD' + pCost;
grandtotalEl.innerHTML = 'USD' + (dCost + wCost + pCost);
},
runLate: function() {
window.setTimeout(updater.run, 0);
}
}
})();
window.onload = updater.setup;
</script>
<form>
<table>
<tr>
<td colspan="4">Please enter whole numbers only.
<tr>
<td>Distance (km)
<td><input type="text" id="distance" value="1">
<td id="dresult">
<td> First km is USD30,000, additional km are USD1,000 each
<tr>
<td>Weight (kg)
<td><input type="text" id="weight" value="0">
<td id="wresult">
<td>No extra fee for goods under 5kg
<tr>
<td>Urgent?
<td><input type="checkbox" id="priority">
<td id="presult">
<td>Urgent goods USD5,000 extra
<tr>
<td>Total to pay:
<td>
<td id="grandtotal">
<td>
<tr>
<td><input id="resetButton" type="reset">
<td><input type="submit">
<td id="updateCell">
<td>
</table>
</form>
--
Rob
No comments:
Post a Comment