Anshul Sanghi Anshul Sanghi - 1 month ago 16
Javascript Question

A particular condition is being skipped in javascript

I am trying to make a javascript price calculator that takes in values from a form consisting no text fields but only radio buttons and checkboxes. Here is my JavaScript:

service = 0;

var setPoint = function (elem) {
var $e = $(elem);
var points = $e.attr("data-points");
switch ($e.attr("name")) {
case 'group1':
group1 = parseFloat(points);
case 'group2':
group2 = parseFloat(points);
case 'group4':
group4 = parseFloat(points);
case 'group5':
group5 = parseFloat(points);
case 'services':
if ($(elem).attr('checked1') == 'true') {
$(elem).attr("checked1", "false");
service = parseFloat(service) - parseFloat(points);
} else {
$(elem).attr("checked1", "true");
service = parseFloat(service) + parseFloat(points);
}
}
}

var calculatePoints = function () {
var total;
var values = [group1, group2, group4, group5, service];

values.map(function (value) {
if (value == "" || value == undefined || value == NaN) {
value = 0;
return value;
}
});

if (service == 0) {
window.alert("At least one service needs to be selected!");
console.log("Service = 0");
} else if (service <= 20) {
total = group1 + group2 + group4 + group5 + service;
} else if (service > 20 && service <= 40) {
total = group1 + group2 + group4 + group5 + (service * 0.8);
} else total = group1 + group2 + group4 + group5 + (service * 0.7);

console.log(total * 1000);

return false;
}


But somehow, the conditional statement
if (service==0)
is not working at all!

I am calling the setPoints function using onclick method in my HTML upon each click on a form field and calculatePoints function using onsubmit. I have made sure that the page doesn't get refreshed when using onsubmit.

I dont know what is wrong with my code and why it is happening so an explaination along with your solutions would me much helpful. You can find a codepen with complete code here : http://codepen.io/anshap1719/pen/pNjepV

Answer

Try to end each case with a break statement into the switch case.

switch ($e.attr("name")) {
    case 'group1':
        group1 = parseFloat(points);
        break;
    case 'group2':
        group2 = parseFloat(points);
        break;
    case 'group4':
        group4 = parseFloat(points);
        break;
    case 'group5':
        group5 = parseFloat(points);
        break;
    case 'services':
        if ($(elem).attr('checked1') == 'true') {
            $(elem).attr("checked1", "false");
            service = parseFloat(service) - parseFloat(points);
        } else {
            $(elem).attr("checked1", "true");
            service = parseFloat(service) + parseFloat(points);
        }
        break;
}