How to update the total amount when tip is selected - javascript

I'm creating a simple food delivery service. I'm trying to figure out how to update total amount when tip is selected
if(choiceRegular.checked == true) {
var totalPrice = choiceRegular.value;
}else if (choicePremium.checked == true) {
totalPrice = choicePremium.value;
}else if(choiceRoyal.checked == true) {
totalPrice = choiceRoyal.value;
}else {
totalPrice = 0;
}
if(tenTip.checked == true) {
var tipPrice = tenTip.value * totalPriceNum
} else if(fiveTip.checked == true) {
tipPrice = fiveTip.value
} else if(twentyTip.checked == true) {
tipPrice = twentyTip.value
} else {
tipPrice = 0
}
totalPriceNum = Number(totalPrice);
tipPriceNum = Number(tipPrice);
document.getElementById('total-amount').innerHTML = '$'+totalPriceNum;

Without understanding the full scope I think in your case totalPriceNum = Number(totalPrice) + Number(tipPrice); would be the combined total.
If values for totalPrice and tipPrice have already been declared you might want to make it a function in JS
as a function e.g.:
function refreshTotal(){
var totalNumBeforeTip = Number(totalPrice);
if(tenTip.checked == true) {
var tipPrice = tenTip.value * totalPriceNum
} else if(fiveTip.checked == true) {
var tipPrice = fiveTip.value
} else if(twentyTip.checked == true) {
var tipPrice = twentyTip.value
} else {
var tipPrice = 0;
}
var tipPriceNum = Number(tipPrice);
var combinedTotal = totalNumBeforeTip + tipPrice;
var priceResultElement = document.getElementById('total-amount');
priceResultElement.innerHTML = '$'+combinedTotal;
}
in the html something like:
add $5 tip <input type="checkbox" id="tip-5" value="5.00" onChange="refreshTotal()">

Try this
HTML
<input id="tenTip" class="tipSelector" name="tip" data-tip-value="10" type="radio" />
<input id="fiveTip" class="tipSelector" name="tip" data-tip-value="5" type="radio" />
<input id="twentyTip" class="tipSelector" name="tip" data-tip-value="20" type="radio" />
JS
const totalAmount = document.getElementById('total-amount');
document.querySelectorAll('.tipSelector').forEach(tipSelector => {
tipSelector.onclick = () => {
totalAmount.innerHTML = totalPriceNum * (1 + tipSelector.dataset.tipValue / 100);
}
})

Related

Too much recursion - radio button - jquery

I have a dynamic form and in that many fields I want to be autocalculated when user goes on with the form. In the form I have 2 radio button mrp and rate. By default mrp is selected. If user doesn't change the default button selected, the value totalCst will be calculated as qty*mrp*cstpercent of all the rows.
If user selects rate radiobutton the value will be calculated as qty*rate*cstpercent of all the rows. I'll add the onchange event later. First I want to get the value totalCst calculated on mrp only or rate whichever is selected.
Radio Button code -
<div class="form-group pull-right">
<label class="radio-inline"><input type="radio" name="taxon" id="mrp" value="mrp" checked="checked">MRP</label>
<label class="radio-inline"><input type="radio" name="taxon" id="rate" value="rate">Rate</label>
</div>
JS
<?php
/* start getting the total amount */
$this->registerJs('
function getSum() {
var sum = 0;
var totalDiscount = 0;
var totalMrp = 0;
var totalCst = 0;
var totalWbst = 0;
var totalCstonamount = 0;
var totalWbstonamount = 0;
var totalCstonmrp = 0;
var totalWbstonmrp = 0;
var cstperValue = $(".cstPercent").val();
var wbstperValue = $(".wbstPercent").val();
var selectedValue = $("input[name=taxon]:checked").val();
alert(selectedValue);
var items = $(".item");
items.each(function (index, elem) {
var qtyValue = $(elem).find(".qty").val();
var rateValue = $(elem).find(".rate").val();
var discValue = $(elem).find(".disc").val();
var mrpValue = $(elem).find(".mrp").val();
var freeValue = $(elem).find(".free").val();
sum = (parseFloat(sum) + (parseFloat(qtyValue) * parseFloat(rateValue))).toFixed(2);
totalDiscount = (parseFloat(totalDiscount) + ((parseFloat(qtyValue) * parseFloat(rateValue) * parseFloat(discValue))/100)).toFixed(2);
totalMrp = (parseFloat(totalMrp) + ((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue))).toFixed(2);
totalCstonamount = (parseFloat(totalCst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonamount = (parseFloat(totalWbst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(wbstperValue))/100).toFixed(2);
totalCstonmrp = (parseFloat(totalCst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonmrp = (parseFloat(totalWbst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(wbstperValue))/100).toFixed(2);
});
if(isNaN(sum) || sum.length == 0) {
sum = 0;
}
if(isNaN(totalDiscount) || totalDiscount.length == 0) {
totalDiscount = 0;
}
if(isNaN(totalMrp) || totalMrp.length == 0) {
totalMrp = 0;
}
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
if(isNaN(totalWbstonamount) || totalWbstonamount.length == 0) {
totalWbstonamount = 0;
}
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
if(isNaN(totalWbstonmrp) || totalWbstonmrp.length == 0) {
totalWbstonmrp = 0;
}
$(".sum").val(sum);
$(".totalDiscount").val(totalDiscount);
$(".totalMrp").val(totalMrp);
if (selectedValue == "mrp") {
getSum();
$(".totalCst").val(totalCstonmrp);
}
else if (selectedValue == "rate") {
getSum();
$(".totalCst").val(totalCstonamount);
}
}
$(".container-items").on("change", function() {
getSum();
});
$(".cstPercent").on("change", function() {
getSum();
});
$(".wbstPercent").on("change", function() {
getSum();
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
getSum();
});
');
/*end getting the total amount */
?>
I'm getting the value selected in alert but too many popup and getting error -
Too much recursion
Updated JS
<?php
/* start getting the total amount */
$this->registerJs('
var totalCstonamount = 0;
var totalWbstonamount = 0;
var totalCstonmrp = 0;
var totalWbstonmrp = 0;
function getSum() {
var sum = 0;
var totalDiscount = 0;
var totalMrp = 0;
var totalCst = 0;
var totalWbst = 0;
// var totalCstonamount = 0;
// var totalWbstonamount = 0;
// var totalCstonmrp = 0;
// var totalWbstonmrp = 0;
var cstperValue = $(".cstPercent").val();
var wbstperValue = $(".wbstPercent").val();
//var selectedValue = $("input[name=taxon]:checked").val();
//alert(selectedValue);
var items = $(".item");
items.each(function (index, elem) {
var qtyValue = $(elem).find(".qty").val();
var rateValue = $(elem).find(".rate").val();
var discValue = $(elem).find(".disc").val();
var mrpValue = $(elem).find(".mrp").val();
var freeValue = $(elem).find(".free").val();
sum = (parseFloat(sum) + (parseFloat(qtyValue) * parseFloat(rateValue))).toFixed(2);
totalDiscount = (parseFloat(totalDiscount) + ((parseFloat(qtyValue) * parseFloat(rateValue) * parseFloat(discValue))/100)).toFixed(2);
totalMrp = (parseFloat(totalMrp) + ((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue))).toFixed(2);
totalCstonamount = (parseFloat(totalCst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonamount = (parseFloat(totalWbst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(wbstperValue))/100).toFixed(2);
totalCstonmrp = (parseFloat(totalCst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonmrp = (parseFloat(totalWbst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(wbstperValue))/100).toFixed(2);
});
if(isNaN(sum) || sum.length == 0) {
sum = 0;
}
if(isNaN(totalDiscount) || totalDiscount.length == 0) {
totalDiscount = 0;
}
if(isNaN(totalMrp) || totalMrp.length == 0) {
totalMrp = 0;
}
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
if(isNaN(totalWbstonamount) || totalWbstonamount.length == 0) {
totalWbstonamount = 0;
}
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
if(isNaN(totalWbstonmrp) || totalWbstonmrp.length == 0) {
totalWbstonmrp = 0;
}
$(".sum").val(sum);
$(".totalDiscount").val(totalDiscount);
$(".totalMrp").val(totalMrp);
// if (selectedValue == "mrp") {
// getSum();
// $(".totalCst").val(totalCstonmrp);
// }
// else if (selectedValue == "rate") {
// getSum();
// $(".totalCst").val(totalCstonamount);
// }
}
function getSumonclick(){
}
$(".container-items").on("change", function() {
getSum();
});
$(".cstPercent").on("change", function() {
getSum();
});
$(".wbstPercent").on("change", function() {
getSum();
});
getSum();
var selectedValue = $("input[name=taxon]:checked").val();
// var totalCstonamount = 200;
// var totalWbstonamount = 0;
// var totalCstonmrp = 100;
// var totalWbstonmrp = 0;
if (selectedValue == "mrp") {
getSum();
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
$(".totalCst").val(totalCstonmrp);
}
else if (selectedValue == "rate") {
getSum();
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
$(".totalCst").val(totalCstonamount);
}
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
getSum();
});
');
/*end getting the total amount */
?>
As per my understanding, Now the issue turns out to be to get the calculated values from inside of getSum function to outside of it.
First I want to get the value totalCst calculated on mrp only or rate
whichever is selected.
You can use the ternary operator here, rather than if... else...:
var factor = (factorMrp.checked ? 'mrp' : 'rate');
Working Example:
var factors = document.getElementById('factors');
var factorMrp = document.getElementById('mrp');
var factorRate = document.getElementById('rate');
var paragraph = document.getElementsByTagName('p')[0];
factorMrp.checked = true;
function checkFactor() {
var factor = (factorMrp.checked ? 'mrp' : 'rate');
paragraph.textContent = 'The value totalCst will be calculated as qty * ' + factor + ' * cstpercent of all the rows.';
}
factors.addEventListener('change',checkFactor,false);
window.addEventListener('load',checkFactor,false);
fieldset {
display: inline-block;
}
<form>
<fieldset id="factors">
<label class="radio-inline"><input type="radio" name="taxon" id="mrp" value="mrp" checked="checked">MRP</label>
<label class="radio-inline"><input type="radio" name="taxon" id="rate" value="rate">Rate</label>
</fieldset>
</form>
<p></p>

Javascript condition not working as expected

I have a JS code which works fine when
checkQueryString != "M"
but When the value becomes checkQueryString == "M" it doesn't goes inside the loop
Here is my code.
function GridExpInfo_ClientAdd(record) {
var checkQueryString = '<%= Request.QueryString["Mode"] %>';
if (checkQueryString != "M") {
if ($('input:checked').length > 0) {
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefNo").disabled = true;
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefDt").disabled = true;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').value = "";
var last_value = 0;
var last_text;
var checkboxlist = document.getElementById('ddlStatus');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('label');
for (i = 0; i < checkOptions.length; i++) {
if (checkOptions[i].checked == true) {
last_text = listSelected[i].innerText;
last_value = checkOptions[i].value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').innerHTML = "";
var ObjPriOptionExp = document.createElement("OPTION");
ObjPriOptionExp.text = last_text;
ObjPriOptionExp.value = last_value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').add(ObjPriOptionExp);
}
}
}
if(checkQueryString == "M")
{
alert('Value is M now');
}
else {
alert('Kindly select the stage');
}
}
}
So my question is, why it doesn't goes inside if when it matches to M
Because
if (checkQueryString == "M") {
alert('Value is M now');
} else {
alert('Kindly select the stage');
}
Has inside if (checkQueryString == "M")
So try this
function GridExpInfo_ClientAdd(record) {
var checkQueryString = '<%= Request.QueryString["Mode"] %>';
if (checkQueryString != "M") {
if ($('input:checked').length > 0) {
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefNo").disabled = true;
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefDt").disabled = true;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').value = "";
var last_value = 0;
var last_text;
var checkboxlist = document.getElementById('ddlStatus');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('label');
for (i = 0; i < checkOptions.length; i++) {
if (checkOptions[i].checked == true) {
last_text = listSelected[i].innerText;
last_value = checkOptions[i].value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').innerHTML = "";
var ObjPriOptionExp = document.createElement("OPTION");
ObjPriOptionExp.text = last_text;
ObjPriOptionExp.value = last_value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').add(ObjPriOptionExp);
}
}
}
} else if (checkQueryString == "M") {
alert('Value is M now');
} else {
alert('Kindly select the stage');
}
}

Disable input on check/uncheck of checkbox

I have 2 checkboxes and 2 input tags for mail and phone.
My requirement is such that I want to disable the input of phone when I check mail and vice-versa. But on checking both the checkboxes I want to keep both the inputs enabled.
Here's my fiddle. This is the code which is not working on the fiddle as I've never used it before. But it is working on my localhost.
The problem is, it's not working well when I check both boxes and then check-unchek many times.
HTML
<input type="checkbox" id="check_email" name="check_email" onchange="disablePhone()" /> Email
<input type="checkbox" id="check_phone" name="check_phone" onchange="disableEmail()" /> Phone
Script
var chk_mail = 0;
var chk_phone = 0;
var unchk = 0;
function disablePhone()
{
if(unchk == 1)
{
document.getElementById("ref_email").disabled = true;
unchk = 0;
//alert("disablePhone")
}
if(chk_mail == 0 && unchk == 0)
{
if(document.getElementById("check_email").checked == true)
{
document.getElementById("form-field-phone").disabled = true;
chk_mail = 1;
}
}
else if( chk_mail == 1 && unchk == 0)
{
document.getElementById("check_email").checked = false;
document.getElementById("form-field-phone").disabled = false;
chk_mail = 0;
}
if(chk_phone ==1 && chk_mail == 1)
{
document.getElementById("ref_email").disabled = false;
document.getElementById("form-field-phone").disabled = false;
chk_phone = 0;
unchk = 1;
}
}
function disableEmail()
{
if(unchk == 1)
{
document.getElementById("form-field-phone").disabled = true;
unchk = 0;
//alert("disableEmail")
}
if(chk_phone == 0 && unchk == 0)
{
if(document.getElementById("check_phone").checked == true)
{
document.getElementById("ref_email").disabled = true;
chk_phone = 1;
}
}
else if(chk_phone == 1 && unchk == 0)
{
document.getElementById("check_phone").checked = false;
document.getElementById("ref_email").disabled = false;
chk_phone = 0;
}
if(chk_phone ==1 && chk_mail == 1)
{
document.getElementById("ref_email").disabled = false;
document.getElementById("form-field-phone").disabled = false;
chk_phone = 0;
unchk = 1;
}
}
I added eventlisteners in the JS and altered the logics a bit. The script fist checks if both boxes are checked. It true, then make both fields enabled. If not disable the right field.
(function() {
document.getElementById('check_email').addEventListener('change', disableInput, false);
document.getElementById('check_phone').addEventListener('change', disableInput, false);
function disableInput() {
var emailChecked = document.getElementById('check_email');
var phoneChecked = document.getElementById('check_phone');
var email = document.getElementById('ref_email');
var phone = document.getElementById('form-field-phone');
if(emailChecked.checked == phoneChecked.checked) {
email.disabled = false;
phone.disabled = false;
} else if(emailChecked.checked) {
phone.disabled = true;
} else {
email.disabled = true;
}
}
})();
<input type="checkbox" id="check_email" name="check_email" /> Email
<input type="checkbox" id="check_phone" name="check_phone" /> Phone
<br>
<input type="email" id="ref_email" name="ref_email" placeholder="Email ID" />
<input type="text" id="form-field-phone" name="form-field-phone" placeholder="Phone"/>
The below code is the solution for you issue .
fiddle here - Working perfect
- JavaScript
`
<script type="text/javascript">
$(document).ready(function () {
$("#check_email").click(function () {
call();
});
$("#check_phone").click(function () {
call();
});
function call() {
document.getElementById("form-field-phone").disabled = false;
document.getElementById("ref_email").disabled = false;
if ($("#check_email").is(':checked') && $("#check_phone").is(':checked')) {
document.getElementById("form-field-phone").disabled = false;
document.getElementById("ref_email").disabled = false;
}
else {
if ($("#check_email").is(':checked')) {
document.getElementById("form-field-phone").disabled = true;
document.getElementById("ref_email").disabled = false;
}
if ($("#check_phone").is(':checked')) {
document.getElementById("form-field-phone").disabled = false;
document.getElementById("ref_email").disabled = true;
}
}
}
});
</script>
`
I test this on JSFiddle and I find that isn't work! But In the SOF Editor. It works!
Your code haven't bug. Maybe it's JSFiddle defect.
function checkDisable(){
var checkEmail = document.getElementById('check_email');
var checkPhone = document.getElementById('check_phone');
var inputEmail = document.getElementById('ref_email');
var inputPhone = document.getElementById('form-field-phone');
if(checkEmail.checked){
inputPhone.disabled = true;
}
if(checkPhone.checked){
inputEmail.disabled = true;
}
if(checkEmail.checked && checkPhone.checked){
inputEmail.disabled = false;
inputPhone.disabled = false;
}
if(!checkEmail.checked && !checkPhone.checked){
inputEmail.disabled = false;
inputPhone.disabled = false;
}
}
<input type="checkbox" id="check_email" name="check_email" onchange="checkDisable()" />
Email
<input type="checkbox" id="check_phone" name="check_phone" onchange="checkDisable()" />
Phone
<br>
<input type="email" id="ref_email" name="ref_email" placeholder="Email ID" />
<input type="text" id="form-field-phone" name="form-field-phone" placeholder="Phone"/>

Javascript Check variable.Then gain ++ per second

I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}

Issue with displaying the correct output. JS radio button selection and addition

So I have this code:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<input type="radio" id="radiobtn1" name="bubbles" onclick="CalculatePrice();"> Less Than 10 Bubbles<br />
<input type="radio" id="radiobtn2" name="bubbles" onclick="CalculatePrice();"> 10 Bubbles<br />
<input type="radio" id="radiobtn3" name="bubbles" onclick="CalculatePrice();"> More than 10 Bubbles<br />
<br />
<input type="radio" id="radiobtn4" name="hours" onclick="CalculatePrice();"> 1 Hour<br />
<input type="radio" id="radiobtn5" name="hours" onclick="CalculatePrice();"> 2 Hours<br />
<input type="radio" id="radiobtn6" name="hours" onclick="CalculatePrice();"> Any Longer<br />
<br />
<input type="checkbox" id="radiobtn7" name="bubbles" onclick="CalculatePrice();"> Inflatable Goals<br />
<input type="checkbox" id="radiobtn8" name="bubbles" onclick="CalculatePrice();"> Icey Cold Bottled Water<br />
<input type="checkbox" id="radiobtn9" name="bubbles" onclick="CalculatePrice();"> Photo and Video Package<br />
<script>
function CalculatePrice() {
var a, b;
var c = 0;
var d = 0;
var e = 0;
var price;
if($(radiobtn1).is(':checked')) {
a = 0;
// alert(a);
}
else if($(radiobtn2).is(':checked')) {
a = 1;
//alert(a);
}
else if($(radiobtn3).is(':checked')) {
a = 0;
//alert(a);
}
if($(radiobtn4).is(':checked')) {
b = 350;
//alert(b);
}
else if($(radiobtn5).is(':checked')) {
b = 450;
//alert(b);
}
else if($ (radiobtn6).is(':checked')) {
b = 0;
// alert(b);
}
if($(radiobtn7).is(':checked')) {
c = 50;
//alert(b);
}
else if($(radiobtn8).is(':checked')) {
d = 20;
//alert(b);
}
else if($ (radiobtn9).is(':checked')) {
e = 50;
// alert(b);
}
if(a == 0)
{
price = 0;
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
//alert(price);
}
else if (b == 0)
{
price = 0;
// alert(price);
}
else
{
price = b;
price = price + new Number(c) + new Number(d) + new Number(e);
if(price != undefined)
{
price = "$" + price;
//document.getElementById('output').innerHTML = '$';
document.getElementById('output').innerHTML = price;
}
else if(a == 0)
{
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
}
}
}
</script>
<br /><br />
<div id="output" style="font-weight:normal;color:#000000;letter-spacing:0pt;word-spacing:-2pt;font-size:36px;text-align:left;font-family:helvetica, sans-serif;line-height:1;"></div>
I am having trouble with the output of CalculatePrice() displaying $NaN or not adding the checkboxes. I have looked over it many times and still can't seem to work out what the issue is. I have all the checkboxes being added if they were selected but it only seems to add 1 and then not the rest. Not sure what to do!
Any help would be appreciated! Thanks.
Two things:
Change code similar to $(radiobtn1) to $("#radiobtn1"). You're referencing an id, and that's the syntax you use to do so.
Instead of calling the function from within the html, call it from the JS using jQuery's .change() function.
jQuery
$('input').change(function(){
CalculatePrice();
});
function CalculatePrice() {
var a, b;
var c = 0;
var d = 0;
var e = 0;
var price;
if ($("#radiobtn1").is(':checked')) {
a = 0;
//alert(a);
} else if ($("#radiobtn2").is(':checked')) {
a = 1;
//alert(a);
} else if ($("#radiobtn3").is(':checked')) {
a = 0;
//alert(a);
}
if ($("#radiobtn4").is(':checked')) {
b = 350;
//alert(b);
} else if ($("#radiobtn5").is(':checked')) {
b = 450;
//alert(b);
} else if ($("#radiobtn6").is(':checked')) {
b = 0;
// alert(b);
}
if ($("#radiobtn7").is(':checked')) {
c = 50;
//alert(b);
} else if ($("#radiobtn8").is(':checked')) {
d = 20;
//alert(b);
} else if ($("#radiobtn9").is(':checked')) {
e = 50;
// alert(b);
}
if (a == 0) {
price = 0;
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
//alert(price);
} else if (b == 0) {
price = 0;
// alert(price);
} else {
price = b;
price = price + new Number(c) + new Number(d) + new Number(e);
if (price != undefined) {
price = "$" + price;
//document.getElementById('output').innerHTML = '$';
document.getElementById('output').innerHTML = price;
} else if (a == 0) {
document.getElementById('output').innerHTML = "Contact Us For Pricing.";
}
}
}
Fiddle
The math is still a little strange, so I'd check that.

Categories

Resources