简体   繁体   中英

How do you call a specific value from inside a math function?

In this code I add a number of values based on a form and subtract the lowest value which creates a new total. The code works great. What I would like to do is instead of only having the new total at the bottom, I would like 3. One that says the original Total without the subtraction, One with the value of the lowest price that I subtract, and then finally the actual new total. As of now it is only displaying the new total.

Example: There are 3 items a scarf for $5, a hat for $10, and a jacket for $20. I add all the values which equals $35, I then subtract the lowest value which is the scarf for $5 and get a new total of $30. I want to display this at the bottom.

Total: $35 Discount: $-5 New Total: $30

The function already figures out all these values, I just don't know how to call them from the function.

// All selected prices are stored on a array
var prices = [];

// A function to remove a item from an array
function remove(array, item) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i] == item) {
            array.splice(i, 1);
            return true;
        }
    }
    return false;
}

function calculateSectedDues(checkbox, amount) {
    // We add or remove the price as necesary

if (checkbox.checked) {
    prices.push(amount);
} else {
    remove(prices, amount);
}

// We sum all the prices
var total = 0;
for (var i = 0, len = prices.length; i < len; i++)
    total += prices[i];

// We get the lower one
var min = Math.min.apply(Math, prices);


if(min == Infinity) { min = 0; };

// And substract it
total -= min;

document.grad_enroll_form.total.value = total;

}

Here is some basic code for you that just writes out the values. I still do not agree with your looping for removing elements from an array.

<span id="value"></span>
var prices = [];

function remove(arr,itm){
    var indx = arr.indexOf(itm);
    if (indx !== -1){
        arr.splice(indx,1);
    }
}

function calculateSectedDues(checkbox, amount) {
    if (checkbox.checked === true) {
        prices.push(amount);
    } else {
        remove(prices, amount);
    }

    var total = 0;
    for (var i = 0, len = prices.length; i < len; i++)
        total += prices[i];

    var min = prices.slice().sort(function(a,b){return a-b})[0];
    if(typeof min === 'undefined') min = 0;

    var withDiscount = total - min;
    var discountAmount = withDiscount - total;

    document.querySelector("#value").innerHTML = "Total: $"+total+'<br>';
    document.querySelector("#value").innerHTML += "Discount: $"+discountAmount+'<br>';
    document.querySelector("#value").innerHTML += "New total: $"+withDiscount+'<br>';
}

Run like this:

calculateSectedDues({checked:true},10);
calculateSectedDues({checked:true},20);
calculateSectedDues({checked:true},5);

Gives this output:

Total: $35
Discount: $-5
New total: $30

JSFiddle


Using checkboxes

<label><input type="checkbox" onclick="calculateSectedDues(this,5)" name="Scarf"> <span>Scarf</span><label><br>
<label><input type="checkbox" onclick="calculateSectedDues(this,10)" name="Hat"> <span>Hat</span><label><br>
<label><input type="checkbox" onclick="calculateSectedDues(this,20)" name="Jacket"> <span>Jacket</span><label><br>

<span id="value">Total: $0<br>Discount: $0<br>New total: $0</span>

I don't know what your HTML looks like, but something like this would work. It uses jQuery to grab all checkboxes that are checked and adds the values of those checkboxes to a total and keeps track of the minimum value. Then it returns all three values in a single object.

I'm assuming that the values of your checkboxes are the prices of the items, which may not be true. If not, the idea will still work, you'll just have to do more work to get the correct price.

function calculate() {
    var total = 0, 
        discount = 0
    ;

    $('input[type="checkbox"]:checked').each(function() {
        var val = parseFloat($(this).val());

        if(discount === 0 || val < discount) {
            discount = val; // keep track of minimum
        }

        total += val;
    });

    //return all three values in one object
    return {
        total: total,
        discount: disount,
        discountedPrice: (total - discount)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM