Search code examples
javaspring-bootthymeleaf

Javascript + Thymeleaf doesn't find the form


On the input form, I perform a check of the entered cost value. But running the script can't find the form input input01.

That's how it works:

<form name="form01" th:method="POST" th:action="@{/add-car/new}" th:object="${carEntity}">
        <input type="text" name="input01">
        ...
        <button type="submit" class="btn btn-primary" onclick="check()">Save</button>
    </form>
    <script>
        function check() {
            let inputVal = document.forms["form01"]["input01"].value;
            OK!!!
            ....
        }
    </script>   

But not like this:

<form name="form01" th:method="POST" th:action="@{/add-car/new}" th:object="${carEntity}">
        <input type="text" name="input01" th:field="*{cost}">
        ...
        <button type="submit" class="btn btn-primary" onclick="check()">Save</button>
    </form>
    <script>
        function check() {
            let inputVal = document.forms["form01"]["input01"].value;
            Where Error:
            "Uncaught TypeError: document.forms.form01.input01 is undefined"

            ....
        }
    </script>   

What am I doing wrong?


Solution

  • As per https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html,

    <input type="text" th:field="*{datePlanted}" />
    

    is equivalent to

    <input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}" />
    

    Hence when you add th:field="*{cost}", the form element name and id is getting changed to name="cost" id="cost". so document.forms["form01"]s input element will look like

    <input type="text" name="cost" id="cost">

    Either access the element as

    document.forms["form01"]["cost"]

    Or add a form id like below and your existing code should work.

    <input id="input01" type="text" name="input01" th:field="*{cost}">.

    Hope that helps to solve your problem.