javascript+thymeleaf找不到表单

rekjcdws  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(321)

在输入表单上,我检查输入的成本值。但是运行脚本找不到表单input01。
这就是它的工作原理:

<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>

但不是这样的:

<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>

我做错什么了?

fafcakar

fafcakar1#

根据https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html,

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

相当于

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

所以当你加上 th:field="*{cost}" ,窗体元素名称和id将更改为 name="cost" id="cost" . 所以document.forms[“form01”]的输入元素 <input type="text" name="cost" id="cost"> 或者访问元素作为 document.forms["form01"]["cost"] 或者添加一个如下所示的表单id,您现有的代码应该可以工作。 <input id="input01" type="text" name="input01" th:field="*{cost}"> .
希望这有助于解决你的问题。

相关问题