Calculate and Display Total Amount Based on Checkbox States

Introduction

In web applications where users interact with financial transactions or bookings, dynamically updating the displayed totals based on user selections is crucial for clarity and usability. The following JavaScript/jQuery code accomplishes this by monitoring changes in checkbox states and updating the displayed total amount accordingly.

Code

$("input[name='advamount'], input[name='Rentalamount']").on('change', function () {
    debugger;
    let advChecked = $("input[name='advamount']").is(':checked');
    let rentalChecked = $("input[name='Rentalamount']").is(':checked');
    if (advChecked || rentalChecked) {
        let advValue = parseFloat($(".advAmount").text());
        let rentalValue = parseFloat($(".rentalAmount").text());
        let _preBookAmount = parseFloat($(".preBookAmount").text());
        var TotalAmt = 0;
        if (advChecked && rentalChecked) {
            TotalAmt = advValue + rentalValue + _preBookAmount;
        } else if (advChecked) {
            TotalAmt = advValue + _preBookAmount;
        } else if (rentalChecked) {
            TotalAmt = rentalValue + _preBookAmount;
        }
        $(".ParaTotalAmountDiv").css("display", "block");
        if (TotalAmt > 0) {
            $(".lblTotalPayableAmount").text("Amount to be paid");
            $(".totalPayableAmount").text(TotalAmt);
        } else {
            $(".lblTotalPayableAmount").text("Amount to be refunded");
            $(".totalPayableAmount").text(Math.abs(TotalAmt));
        }
        console.log('Advance Amount:', advValue);
        console.log('Rental Amount:', rentalValue);
    } else {
        $(".ParaTotalAmountDiv").css("display", "none");
        $(".totalPayableAmount").text(""); // Clear the total amount display when unchecked
    }
});

1. Event binding and checkbox state management

  • The script listens for changes in checkboxes with names advamount and Rentalamount. Each checkbox represents a financial component that users can select.
  • When either checkbox changes, the script updates its internal state (advChecked and rentalChecked) to reflect whether the respective checkbox is checked or not.

2. Calculation of total amount

  • Upon detecting a change in checkbox state (change event), the script fetches numeric values (advValue, rentalValue, and _preBookAmount) from HTML elements (identified by their classes: .advAmount, .rentalAmount, and .preBookAmount).
  • Depending on whether one or both checkboxes are checked, it calculates the total amount (TotalAmt) that includes the selected financial components and any pre-booked amounts.

3. Display management

  • If at least one checkbox is checked (advChecked or rentalChecked is true), it ensures that the container (ParaTotalAmountDiv) displaying the total amount is visible (display: block).
  • If neither checkbox is checked, the container is hidden (display: none), and the displayed total amount is cleared to maintain a clear user interface.

4. UI update based on total amount

Depending on whether TotalAmt is positive (indicating an amount to be paid) or zero/negative (indicating a refund or no additional payment required), the script updates UI elements (lblTotalPayableAmount and totalPayableAmount) to reflect the appropriate message and value.

5. Logging for debugging

Optional logging statements (console.log) provide real-time feedback in the browser’s console, displaying the values of advValue and rentalValue for each change event. This aids in debugging and tracking the script’s behavior.

Conclusion

By dynamically updating the displayed total amount based on user interactions with checkboxes, this script enhances user experience by providing real-time feedback on financial obligations or refunds. It ensures clarity and transparency in financial transactions within web applications, improving overall usability and user satisfaction.