How do I subtract the value of a javascript variable when form element is unchecked

13,409

Try :

function updateAmount(amount) {
    $amount = $('#amount'); // cache for later use
    if ($('#reservationfee0').is(':checked')) {
        $amount.val(parseInt($amount.val(), 10) + amount);
    } else {
        $amount.val(parseInt($amount.val(), 10) - amount);
    }
}​

Working example here

this checks if the checkbox is checked using .is() if it is then the amount is added to the current value if not its subtracted.

Also note that parseInt takes a second parameter - radix its recommended that you include this value to be certain of results ... docs for parseInt here

Share:
13,409
Keith S.
Author by

Keith S.

I'm a freelance web developer with a focus on WordPress. I also dabble in joomla.

Updated on June 04, 2022

Comments

  • Keith S.
    Keith S. almost 2 years

    Note, this isn't my code, or the actual code in the form. This is just my testing version, but does represent what I want to do.

    Given the following code, how can I get the script to subtract the passed value when the checkbox is unselected:

    <!DOCTYPE html>
    <html lang="en">
    
        <head>
            <title>form test</title>
            <script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
            <script type="text/javascript">
                function updateAmount(amount) {
                    parseInt(amount);
                    if ($('#amount').val()) {
                        parseInt(amount);
                        amount = amount + parseInt($('#amount').val());
                    }
                    $('#amount').val(amount);
                    alert('Amount: ' + $('#amount').val());
                }
            </script>
        </head>
    
        <body>
            <form action="" method="post" name="form-test">
                <input onclick="updateAmount(150)" class="inputbox" id="reservationfee0"
                value="Registration Fee" type="checkbox" />
                <strong>$150</strong>Reservation Fee</form>
        </body>
    
    </html>
    

    As it stands, whoever coded the function didn't take into account that people might check and uncheck that box before they submit the form (which includes more fields and other numbers that get added into the amount variable before submission). There has been a couple of reports of over-charges due to this, so I need to figure out how to stop it from happening, but I know very little about javascript/jquery.