我只想实现,select选择用户,然后把用户姓名和ID都传到后端。然鹅thymeleaf+layui要实现这个逻辑,非常繁琐
- thymeleaf遍历变量,渲染option
- option里,用户姓名可以很自然地传上去,但是id就没法了,得在attr里加上item.id
- 然后监听select事件,获取选中的option,把option的这个id设置到隐藏的input上
- 最后获取所有input,表单提交
不得不说这种方式,实在是原始
<div class="layui-form-item additional-input" id="new-chief" hidden>
<label class="layui-form-label"> <span style="color: red">*</span> 新负责人姓名</label>
<div class="layui-input-block">
<input type="text" name="newChiefId" autocomplete="off" placeholder="新负责人姓名" class="layui-input" hidden>
<select name="newChief" lay-filter="newChief">
<option th:each="item : ${users}" th:text="${item.nickname}" th:value="${item.nickname}" th:attr="newChiefId=${item.id}"></option>
</select>
</div>
</div>
<div class="layui-form-item additional-input" id="new-dept" hidden>
<label class="layui-form-label"> <span style="color: red">*</span> 新项目管理单位</label>
<div class="layui-input-block">
<input type="text" name="newDeptId" autocomplete="off" placeholder="新项目管理单位" class="layui-input" hidden>
<select name="newDept" lay-filter="newDept">
<option th:each="item : ${depts}" th:text="${item.deptName}" th:value="${item.deptName}" th:attr="newDeptId=${item.id}"></option>
</select>
</div>
</div>
//新负责人id绑定
form.on('select(newChief)', function (data) {
let newChiefId = $('select[name="newChief"] option:selected').attr("newChiefId")
$('#newChiefId').val(newChiefId)
return false;
});
//新部门id绑定
form.on('select(newDept)', function (data) {
let newDeptId = $('select[name="newDept"] option:selected').attr("newDeptId")
$('#newDeptId').val(newDeptId)
return false;
});