Macness
Macness

Reputation: 1226

Subtotaling in jquery function (.click issues?)

This function only subtotals my last value clicked when I use the .hasVal class with a radio button. Any ideas?

Update: Here's the jsfiddle link: http://jsfiddle.net/SUKsM/4/

Essentially my HTML form has a fieldset with values:

<fieldset id="breadOptions" class="hidden">
    <legend>Select one</legend>
    <input type="radio" name="breadType" id="breadWhite" class="hasVal" value=".5,260" /> White (260 calories)<br />
    <input type="radio" name="breadType" id="breadWheat" class="hasVal" value=".5,360" /> Wheat (360 calories)<br />
</fieldset>​

An here's the script:

$(function () {
    var basePrice = 3;
    var totalCal = 0;
    var taxRate = .07;
    $('#total').text(basePrice.toFixed(2));
    $('#sub').text(basePrice.toFixed(2));
    $('#cal').text(totalCal);
    $('#tax').text((taxRate * 100).toFixed(2));

    $('.hasVal').click(function () {
        var price = 0;
        var totalCal = 0;
        var tar = event.currentTarget;
        var optArr = tar.value.split(','); //cost,calorie

        price += parseFloat(optArr[0]);
        totalCal += parseInt(optArr[1]);

        $(':checked').each(function () {
            totalPrice = (price + basePrice);
        });

        $('#sub').text(totalPrice.toFixed(2));
        $('#cal').text(totalCal);

        totalTax = totalPrice + (totalPrice * taxRate);
        $('#total').text(totalTax.toFixed(2));
    });
});

Upvotes: 0

Views: 83

Answers (2)

DevlshOne
DevlshOne

Reputation: 8457

If I understand you correctly, your complaint that is when you click a radio button, you only get a subtotal displayed that reflects your most recently clicked value. Is this right? It would help if you posted the rest of the HTML code that you're using (I'm assuming that the sandwich has more ingredients than just bread).

For now, I've dropped your code into a jsFiddle : http://jsfiddle.net/devlshone/SUKsM/ with a few changes.

Once you've explained a bit more and supplied some more HTML code, I'll be glad to help you further.

Upvotes: 1

Cymen
Cymen

Reputation: 14429

You could make use of HTML5 data attributes for the price and calories like so:

<input type="radio" ... data-cost=".5" data-cal="260" value="white" /> White (260 calories)
<input type="radio" ... data-cost=".5" data-cal="360" value="wheat" /> Wheat (360 calories)

When you sum the total price and calories, iterate over all the selected radio buttons like so instead of just the current one:

$('input:radio:checked').each(function() {
    var input = $(this);
    price += parseFloat(input.attr('data-cost'), 10);
    cal += parseInt(input.attr('data-cal'), 10);
});

Here is a working example: http://jsfiddle.net/ncCgu/

Here is an example if you can't use HTML5 data attributes: http://jsfiddle.net/z55rd/

Upvotes: 1

Related Questions