How to apply if satement and calculate in JavaScript

180 views Asked by At

How can I apply the if statement and calculate a set of radio buttons using JavaScript?

It works as of now with adding up the total. but I would like it to apply the $150.00 off only when they select yes.

Here is the radio buttons that I am trying to work with.

    <p>Baby Plan<br />
        [radio BPSUBPT id:BPSUBPT class:radio-vertical "Baby Plan $300.00 3 Sessions" "Baby Plan $500.00 4 Sessions"] </p>

    <p>Did you have a Newborn session With ADP? <br />
[radio BPSUPQ id:BPSUPQ class:radio-vertical "Yes $-150 off" "No $000.00"]</p>

    <p>Baby Plan Totals: <br />
    Baby Plan Price: [text BPSUTotal 28/28 id:BPSUTotal]
    Discount Amount: [text BPSUDA 8/8 id:BPSUDA]

    Total Price: <span id="total"></span>

My JavaScript as I have now:

<script>
$(document).ready(function() {
    var inputs = $('input[name="BPSUBPT"], input[name="BPSUPQ"]');
    $(inputs).click(function() {
        var total = 0;
        $(inputs).filter(':checked').each(function() {
            // Now including the - sign
            var value = ($(this).val()).match(/\$(-?[0-9]*)/)[1];
            if (value) {
                // I'm now ADDing the total
                // total = total + parseInt(value);
                total += parseInt(value);
            }
        });
        $('#total').html('$' + total);
          $('#BPSUBA').val('$' + total);
});
    $('input[name="BPSUBPT"]').click(function() {
        $(this).blur();
        $('#BPSUBPP').val($(this).val());
    })
    $('input[name="BPSUPQ"]').click(function() {
        $(this).blur();
        $('#BPSUDA').val($(this).val());
   });
}); 
</script>

I would like to have the radio button that has the value of Yes| $150.00 off to be subtracted from the set of radio buttons from baby plan.

1

There are 1 answers

9
Giri On

Try commenting out your old code and try this instead. Also sometimes when you have two fields with the same name, it could get tricky and sometimes even fail.

$(document).ready(function(){
    var radio1 = $('input[name="BPSUBPT"]');
    var radio2 = $('input[name="BPSUBQ"]');
    var selectedValue = '';
    $(radio1).on('click', function(){
        $(radio1).each(function(index, value){
            var checked = $(this).is(':checked');
            if(checked && index == '0'){
                selectedValue = 300;
                $('#BPSUTotal').val(selectedValue);
            } else if(checked && index == '1'){
                selectedValue = 500;
                $('#BPSUTotal').val(selectedValue);
            }
        });
    });

    $(radio2).on('click', function(){
        var checked = $(this).is(':checked');
        if(checked && selectedValue != ''){
            var oldValue = $('#BPSUTotal').val();
            var newValue = oldValue - 150;
            $('#BPSUTotal').val(newValue);
        }
    });

});