Question

(Rephrasing question from earlier) So here is the assignment:

First, you will have to calculate a cost for the weight of the parcel. The user will enter the total weight of their parcel into the text field. The schedule is as follows…

0 – 150 lbs $20.00 per pound | 151 – 300 lbs $15.00 per pound | 301 – 400 lbs $10.00 per pound Do not allow the user to enter a weight that is < 0 or > 400. If they do, output an error message in red to div#results and ‘return’ out of the function.

Next, the user will choose a discount amount (for whatever reason, does not matter). You will need to apply whatever discount amount is chosen. (50% off, 20% off, none).

This is what I have done so far. Variable aren't declared yet, just wrote them in.

function calcTotal() {

var msg;
var weight = parseInt( document.getElementById("weight").value );
var discount;
var total;

if( weight >= 0 && weight <= 150 ) {

    total = weight * 20 
}   
else if( weight >150 && weight <= 300 ) {

    total = weight * 15 
}   
else if( weight >300 && weight <= 400 ) {

    total = weight * 10 
}

if( document.getElementById("50%").selected == true ) {

total = total * 0.50;
}

if( document.getElementById("25%").selected == true ) {

total = total * 0.25;
}

if( document.getElementById("none").selected == true ) {

total = total;
}

Is this somewhat correct so far?

Can't seem to figure out how to apply the discount based on what the user selects. The discounts are 3 radio buttons. Do i need to apply an id to each radio button?

Was it helpful?

Solution

First of all you need to use && (AND) instead of || (OR) because you want both conditions to be met not just one. First IF statement will process value -1000 as TRUE (as well as any other value because your interval is from 0 to infinity plus from minus infinity to 150) because it satisfies the second part of the first condition.

Second, the formula is correct but you have to convert percents into 0-1 interval. 100% = 1, 0% = 0 and x% = x/100. Then it should work without any problems.

Last thing to do is that you need to pass the values into your function:

function calcTotal(weight, discount) {
    // do the calculation with passed values, you do not need to declare them here anymore
}

Or you need to set values right inside of that function, e.g.:

function calcTotal() {
    var discount = $("#inputField").val();  // using jQuery, where inputField is element
                                            // from which the value is taken e.g. < input >
    ...
}

To display the final output, add this to your function:

$("body").append("<div id='output'>" + output + "</div>"); // using jQuery, watch for single/double quotes

and style it with css to be in the center:

#output {
    position: absolute;
    width: 200px;
    height: 200px;
    left: 50%;
    margin-left: -100px;
    top: 200px;
}

OTHER TIPS

I made a fiddle that you should be able to get what is going on pretty quickly.

http://jsfiddle.net/a58rR/3/

I used a touch of jQuery just to get the bindings on the UI elements.

I hope this is not for a class and you copy this wholesale! ;)

Basically, I put all your Tier pricing into one object.

Tiers = [{
    nPrice: 20,
    nWeightMin: 1,
    nWeightMax: 150
}, {
    nPrice: 15,
    nWeightMin: 151,
    nWeightMax: 300
}, {
    nPrice: 10,
    nWeightMin: 301,
    nWeightMax: 400
}]; 

Then, your function will calculate based on the entered weight and discount selected, determine the Tier, validate the weight, update the UI with a message if out of range, calculate the final price and apply any discount, and update the UI with the total price:

function calculatePrice() {
    console.log('Begin Calc');
    var _nW = document.getElementById('nParcelWeight').value * 1;
    var _nD = document.getElementById('aDiscounts').value * 1;
    var _nP = 0;
    var nTotalPrice = 0;
    var _TotalPrice = document.getElementById('nPrice');
    var _nMaxWt = Tiers[Tiers.length - 1].nWeightMax; 
    // Using the last Tier keeps the max weight dynamic no matter how many tiers you add as long as they are in order

    console.log('Max Weight: ' + _nMaxWt);
    console.log('Weight: ' + _nW);
    console.log('Discount: ' + _nD);

    if (isNaN(_nW) || _nW < 1 || _nW > _nMaxWt) {

        // Throw/Display an out of range error here  
        console.log('Yep, out of range');
        document.getElementById('uiFeedback').innerHTML = 'The number is out of range.';
    } else {
        // reset if valid
        document.getElementById('uiFeedback').innerHTML = '';
    }

    // Find Tier
    for (var i = 0; i < Tiers.length; i++) {
        console.log('we are in loop:' + i);
        if (_nW >= Tiers[i].nWeightMin && _nW <= Tiers[i].nWeightMax) {
            _nP = Tiers[i].nPrice;
            break;
        }
    }
    console.log('Tier: ' + i);
    console.log('Price: ' + _nP);

    // Calculate Discount
    if (_nD != 1) _nD = 1 - _nD; // (20%==.20, but that would be .80 of the Price, etc)

    // Calc Price
    nTotalPrice = (_nP * _nW * _nD);
    _TotalPrice.value = nTotalPrice;
}

The html will look something like this:

<div id='uiFeedback'></div>Parcel Weight:
<input id='nParcelWeight' value='0'>Discount:
<select id='aDiscounts'>
    <option value='1'>none</option>
    <option value='.2'>20%</option>
    <option value='.5'>50%</option>
</select>
<hr>Price:
<input id='nPrice'>

And your CSS at a minimum might just color your messaging:

#uiFeedback {
    color: red;
    font-weight: bold;
}

Here are the bindings, which you could do with inline onChanges or raw js attach events:

$(function () {
    $('#nParcelWeight,#aDiscounts ').on('change', function () {
        calculatePrice();
    });
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top