我的页面上有一个
<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}
不会根据用户输入而更改,否则页面不会对该更改做出反应。
这可以用 Thymeleaf 来做吗,还是我必须使用 JavaScript?
这可以使用 jquery/javascript 来实现。由于 thymeleaf 在服务器端呈现,一旦页面加载到浏览器上,您就只有 html 元素。 为了实现这一目标,请尝试这样的事情 -
最初,您的第二个 div 将被隐藏,并且您希望在每次用户更改选择值时运行一个函数。
<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>
在 jquery 函数中实现隐藏和显示 div 的逻辑 -
函数 hideShowForManufactr(){
var selectCarMnfctr= $('#carManufctrOption').find(":selected").val(); if(selectCarMnfctr == 'Ford'){ $("#fordDivId").show(); }else{ $("#fordDivId").hide(); }
}