如何在Thymeleaf中显示从“选择”到“文本字段”的所选项目?

时间:2019-01-02 15:55:21

标签: java spring spring-boot spring-mvc thymeleaf

我正在使用Thymeleaf开发一个简单的Spring引导应用程序,并希望在“用户名”文本字段中显示Combobox1中的选定“用户”。我怎么做到的?

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>Добавить цитату</title>
</head>
<body>
<form th:action="@{/addQuote}"
  th:object="${personForm}" method="POST">
<p><b>Имя</b><br>
<div>
    <input name = "userName" type="text" size="38" th:field="*{name}" >
    <a style="position:fixed;left:0px;top:0px;margin: 0;border-width:0;z- 
index:255"></a>
</div>
<textarea name="comment" cols="40" rows="6" th:field="*{text}"  >
</textarea>
<p><input type="reset" value="Отменить">
    <input type="submit" value="+"></p>
<select name="Combobox1" size="1" id="Combobox1"
      style="position:absolute;left:17%;top:4%;width:199px;height:20px;z- 
index:3;" >
    <option th:each="user : ${users}"
            th:value="${user}"
            th:utext="${user}"/>
 </select>
</form>
<div th:if="${errorMessage}" th:utext="${errorMessage}"
 style="color:red;font-style:italic;">
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

选项1: 在您的userName输入标记中添加ID

<input id="userName" name = "userName" type="text" size="38" th:field="*{name}" />

添加脚本

<script>
 function check() {
     document.getElementById("userName").value=document.getElementById("Combobox1").value;
    } 
 </script>

调用脚本功能

 <select id="Combobox1"  onChange="check();">

选项2:

Jquery的另一个选项

$(function() { 
  $("#Combobox1").on("change",function() { 
  alert();
    $("#userName").val($(this).val()); 
  }); 
});