Spring Boot Thymeleaf:当用户更改值时,是否可以使用th:if?

n7taea2i  于 7个月前  发布在  Spring
关注(0)|答案(1)|浏览(73)

我的页面上有一个<select>输入和另一个<input>,根据用户在表单中的选择,我想隐藏或显示另一个输入。然而,这两个输入都与模型绑定,并且似乎在运行时卡住了,直到表单提交。
下面是我想要做的,但是当运行页面时,即使我选择了正确的选项,第二个div也不会显示。

<div>
  <label for="model">Model</label>
  <select th:field="*{manufacturer}" th:required="required">
      <option th:value="Ford">Ford</option>
      <option th:value="Tesla">Tesla</option>
      <option th:value="Lotus">Lotus</option>
  </select>
</div>
<div th:if="${car.manufacturer == 'Ford'}">
  <label for="gasType">Gas Type</label>
  <input th:field="*{gasType}" name="gasType" type="text" maxlength="5">
</div>

字符串
这告诉我,*{manufacturer}不会随着用户输入而改变,或者页面不会对这种改变做出React。
这可以用Thymeleaf来做吗?或者我必须使用JavaScript?

kuuvgm7e

kuuvgm7e1#

这可以使用jquery/JavaScript来实现。由于thymeleaf在服务器端呈现,一旦页面加载到浏览器上,您就只有html元素。为了实现,尝试类似这样的东西-
1.最初你的第二个div是隐藏的,你想在每次用户修改select值时运行一个函数。

<div>
  <label for="model">Model</label>
  <select th:field="*{manufacturer}" th:required="required" onChange="hideShowForManufactr()" id="carManufctrOption">
      <option th:value="Ford">Ford</option>
      <option th:value="Tesla">Tesla</option>
      <option th:value="Lotus">Lotus</option>
  </select>
</div>
<div th:if="${car.manufacturer == 'Ford'}" style="display:none" id="fordDivId">
  <label for="gasType">Gas Type</label>
  <input th:field="*{gasType}" name="gasType" type="text" maxlength="5">
</div>

字符串
1.在jquery函数中实现隐藏和显示div的逻辑-
public void run(){

var selectCarMnfctr= $('#carManufctrOption').find(":selected").val();
     if(selectCarMnfctr == 'Ford'){
           $("#fordDivId").show();
      }else{
            $("#fordDivId").hide();
      }


}

相关问题