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

2. Calculation of total amount

3. Display management

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.