我只想实现,select选择用户,然后把用户姓名和ID都传到后端。然鹅thymeleaf+layui要实现这个逻辑,非常繁琐

    • thymeleaf遍历变量,渲染option
    • option里,用户姓名可以很自然地传上去,但是id就没法了,得在attr里加上item.id
    • 然后监听select事件,获取选中的option,把option的这个id设置到隐藏的input上
    • 最后获取所有input,表单提交

    不得不说这种方式,实在是原始

    1. <div class="layui-form-item additional-input" id="new-chief" hidden>
    2. <label class="layui-form-label"> <span style="color: red">*</span> 新负责人姓名</label>
    3. <div class="layui-input-block">
    4. <input type="text" name="newChiefId" autocomplete="off" placeholder="新负责人姓名" class="layui-input" hidden>
    5. <select name="newChief" lay-filter="newChief">
    6. <option th:each="item : ${users}" th:text="${item.nickname}" th:value="${item.nickname}" th:attr="newChiefId=${item.id}"></option>
    7. </select>
    8. </div>
    9. </div>
    10. <div class="layui-form-item additional-input" id="new-dept" hidden>
    11. <label class="layui-form-label"> <span style="color: red">*</span> 新项目管理单位</label>
    12. <div class="layui-input-block">
    13. <input type="text" name="newDeptId" autocomplete="off" placeholder="新项目管理单位" class="layui-input" hidden>
    14. <select name="newDept" lay-filter="newDept">
    15. <option th:each="item : ${depts}" th:text="${item.deptName}" th:value="${item.deptName}" th:attr="newDeptId=${item.id}"></option>
    16. </select>
    17. </div>
    18. </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;
            });