'How do I call my javascript function when using thymeleaf?

I want to perform a subtraction where the values will come from two and subtract them, then display the result to another textbox. However, I can't seem to call my js function when using the th:onclick.

        <div class="mt-3 row g-3">
            <div class="col-md-6">
                <a th:href="@{~/records/add}"><button type="button" class="btn btn-secondary">Add Record</button></a>
                <a th:href="@{~/records/graph}"><button type="button" class="btn btn-secondary">Generate Graph</button></a>
                <a th:onclick="fnCalculate()" ><button type="button" class="btn btn-secondary">Calculate Budget</button></a>
            </div>
            <div class=" col-md-6 ">
                <h6>Total Expenses: </h6>
                <textarea class="form-control" id="totalExpense" name="totalExpense" th:text="${#aggregates.sum(records.![price])}"></textarea>

                <h6 class="mt-2">Current Budget: </h6>
                <textarea type="text" class="form-control mb-2" id="currentBudget" name="currentBudget"></textarea>

                <h6 class="mt-2">Remaining Budget: </h6>
                <textarea type="text" class="form-control mb-5" id="remainingBudget" disabled></textarea>
            </div>
        </div>
    </div>
</main>

<script th:inline="javascript">
    function fnCalculate(txt1, txt2) {
        txt1 = parseInt(document.getElementById("currentBudget").value);
        txt2 = parseInt(document.getElementById("totalExpense").value);
        document.getElementById("remainingBudget").innerHtml = txt1 - txt2;
    }
</script>


Solution 1:[1]

Do not call the function, just use the function reference

<!--  Excluding the brackets `()` -->
<a th:onclick="fnCalculate" ><button type="button" class="btn btn-secondary">Calculate Budget</button></a>
            </div>

Besides, onClick will send it's own parameter [Event][1] in the fnCalculate function. so you won't get txt1 & txt2 as parameter as you expected.

Adjust your javascript implementation accordingly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ratul Sharker