cryptohustla cryptohustla - 9 months ago 25
jQuery Question

How to add variables value

Hi guys im sorry but i dont even know what the title should be i have this script that works perfectly but i had this problem that i really cant solve cause im not really that good with programming. My code simply adds the total value of the customer order somehow the value of each item is stored temporarily on div and then just dynamically print the value in it, the purpose is for me to see if the calculation is working now i am having problem as i want to remove the DIV and leave total only. Here is my code



$(document).ready(function() {

$('input:radio[name="meal-356"]').change(function(ev){

if ($(this).val() == 'Burger with fries') {
var meal = 20;
}
else {
var meal = 30;
}

$('#meal').text((meal).toFixed(2)).trigger('change');

});

$('input:radio[name="drinks-123"]').change(function(ev){

if ($(this).val() == 'Ice Tea') {
var drinks = 1;
}
else if ($(this).val() == 'Coke') {
var drinks = 1.20;
}
else if ($(this).val() == 'Lemonade') {
var drinks = 2;
}
else if ($(this).val() == 'Water') {
var drinks = 1.75;
}
else if ($(this).val() == 'Hot choco') {
var drinks = 3;
}
else if ($(this).val() == 'Hot coffee') {
var drinks = 1.25;
}
else {
var drinks = 0;
}

$('#drinks').text((drinks).toFixed(2)).trigger('change');
});


$('input:radio[name="extras-781"]').change(function(ev){

if ($(this).val() == 'Rice') {
var extras = 10;
}
else if ($(this).val() == 'Gravy') {
var extras = 5;
}
else {
var extras = 0;
}
$('#extras').text((extras).toFixed(2)).trigger('change');
});

$('textarea[name="spoon-112"]').keyup(function(ev){

var spoon = $(this).val().replace(/\n/g, '<br/>');
var spoon = spoon*.25;
$("#spoon").text(spoon).trigger('change');

});

$('input:text[name="fork-143"]').keyup(function(ev){

var fork = $(this).val().replace(/\n/g, '<br/>');
var fork = fork*.5;
$("#fork").text(fork).trigger('change');
});



$('#meal, #drinks, #extras, #spoon, #fork').on('change', function(e) {
var total = $('#meal, #drinks, #extras, #spoon, #fork').toArray().reduce(function(acc, val) {
return acc + +val.textContent ;
}, 0);
$('#total').text(total.toFixed(2));
})

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<h1>Calculator base on radio buttons</h1>
<h2>Question 1: meal</h2>
<div class="meal-wrapper">
<label class="radio"><input name="meal-356" value="Burger with fries" type="radio"/>Burger with fries</label>
</div>
<div>
<label class="radio"><input name="meal-356" value="Chicken with rice" type="radio" />Chicken with rice</label>
</div>

<h2>Question 2: drinks</h2>
<div class="drinks-123-wrapper">
<input type="radio" name="drinks-123" value="Ice Tea" /> Ice Tea
<input type="radio" name="drinks-123" value="Coke" /> Coke
<input type="radio" name="drinks-123" value="Lemonade" /> Lemonade
<input type="radio" name="drinks-123" value="Water" /> Water
<input type="radio" name="drinks-123" value="Hot choco" /> Hot choco
<input type="radio" name="drinks-123" value="Hot coffee" /> Hot coffee
<input type="radio" name="drinks-123" value="No drinks-123" /> No drinks-123
</div>

<h2>Question 3: extras</h2>
<div class="drinks-wrapper">
<input type="radio" name="extras-781" value="Rice" /> Rice
<input type="radio" name="extras-781" value="Gravy" /> Gravy
<input type="radio" name="extras-781" value="No Extra" /> No Extra
</div>

<h2>Question 4: How many extra spoon?</h2>
<div class="spoon-wrapper">
<textarea name="spoon-112" rows="3"></textarea>
</div>

<h2>Question 5: How many extra fork?</h2>
<div class="fork-wrapper">
<input name="fork-143" type="text" value="" placeholder=""/>
</div>

<hr />
<div class="price-wrapper">
<b>meal:</b> <span id="meal"></span>
<div></div>
<b>drinks:</b> <span id="drinks"></span>
<div></div>
<b>extras:</b> <span id="extras"></span>
<div></div>
<b>spoon:</b> <span id="spoon"></span>
<div></div>
<b>fork:</b> <span id="fork"></span>
</div>

<div class="total-wrapper">
<h3>
<b>Total:</b><span id="total"></span>
</h3>
</div>





i want to actually remove the divs with id #meal, #drinks, #extras, #spoon, #fork and just leave #total .. but the problem is it wont calculate anymore and i dont know what to do... this is the code where im stuck

$('#meal, #drinks, #extras, #spoon, #fork').on('change', function(e) {
var total = $('#meal, #drinks, #extras, #spoon, #fork').toArray().reduce(function(acc, val) {
return acc + +val.textContent ;
}, 0);
$('#total').text(total.toFixed(2));
})

Answer Source

You can reduce your code a lot, if you would add the price information in your HTML, for instance with data-price attributes. But as you explained you cannot change the HTML, the second best option would be to store the prices in some object structure.

The suggested code:

// Define the prices for each element selector, and with an 
// indication whether the count must be read from text
var unitPrices = [
//   element selector                       price has-count
    [":checked[value='Burger with fries']", 20.00,  0],
    [":checked[value='Chicken with rice']", 30.00,  0],
    [":checked[value='Ice Tea']",            1.00,  0],
    [":checked[value='Coke']",               1.20,  0],
    [":checked[value='Lemonade']",           2.00,  0],
    [":checked[value='Water']",              1.75,  0],
    [":checked[value='Hot choco']",          3.00,  0],
    [":checked[value='Hot coffee']",         1.25,  0],
    [":checked[value='No drinks-123']",      0.00,  0],
    [":checked[value='Rice']",              10.00,  0],
    [":checked[value='Gravy']",              5.00,  0],
    [":checked[value='No Extra']",           0.00,  0],
    ["[name=spoon-112]",                     0.25,  1],
    ["[name=fork-143]",                      0.50,  1],
];

function updateTotal() {
    // Iterate over all price elements, and apply the unit prices
    var prices = unitPrices.map(function (info) {
        var $elem = $(info[0]);
        // if the element does not match, return 0, else the price
        return $elem.length * info[1] *
            // and see if we need to read out the count        
            // if so: multiply by the entered number (ignore non-digits)
            (info[2] ? $elem.val().replace(/\D/g, '') : 1 );
    });
    // Now we have an array of prices (numbers). Total them:
    var total = prices.reduce(function(acc, val) {
        return acc + val;
    }, 0);
    // Display the total:
    $('#total').text(total.toFixed(2));
}

$(function() {
    // Update the total on any change to input elements:
    $(':input').on('input change', updateTotal);
    // Also call it once when the page loads:
    updateTotal();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1>Calculator base on radio buttons</h1>
<h2>Question 1: meal</h2>
<div class="meal-wrapper">
    <label class="radio"><input name="meal-356" value="Burger with fries" type="radio"/>Burger with fries</label>
</div>
<div>
    <label class="radio"><input name="meal-356" value="Chicken with rice" type="radio" />Chicken with rice</label>
</div>

<h2>Question 2: drinks</h2>
<div class="drinks-123-wrapper">
    <input type="radio" name="drinks-123" value="Ice Tea" /> Ice Tea
    <input type="radio" name="drinks-123" value="Coke" /> Coke
    <input type="radio" name="drinks-123" value="Lemonade" /> Lemonade
    <input type="radio" name="drinks-123" value="Water" /> Water
    <input type="radio" name="drinks-123" value="Hot choco" /> Hot choco
    <input type="radio" name="drinks-123" value="Hot coffee" /> Hot coffee
    <input type="radio" name="drinks-123" value="No drinks-123" /> No drinks-123
</div>

<h2>Question 3: extras</h2>
<div class="drinks-wrapper">
    <input type="radio" name="extras-781" value="Rice" /> Rice
    <input type="radio" name="extras-781" value="Gravy" /> Gravy
    <input type="radio" name="extras-781" value="No Extra" /> No Extra
</div>

<h2>Question 4: How many extra spoons?</h2>
<div class="spoon-wrapper">
    <textarea name="spoon-112" rows="3" ></textarea>
</div>

<h2>Question 5: How many extra forks?</h2>
<div class="fork-wrapper">
    <input name="fork-143" type="text" value="" placeholder=""/>
</div>

<hr />
<div class="total-wrapper">
    <h3>
        <b>Total:</b><span id="total"></span>
    </h3>
</div>

Make sure to run the snippet in full-page mode.