Controller部分
/**
* 修改公告
*/
@GetMapping("/edit/{sid}")
public String edit(@PathVariable("sid") Long sid, ModelMap mmap)
{
mmap.put("classes", classesService.selectClassesAll());
mmap.put("student", studentService.selectStudentById(sid));
//二级联动默认选中
mmap.put("grade", gradeService.selectGradeList(new SysGrade()));
//通过id进行判断并且取值,通过id进行逐层查询获取id,先向上准确查询,在向下模糊查询,默认选中在下面。
int classesId1= studentService.selectStudentById(sid).getCid();
int gradeId1 = classesService.selectClassesById(Long.parseLong(String.valueOf(classesId1))).getGid();
//
mmap.put("abc",classesId1);
mmap.put("cba",gradeId1);
//
mmap.put("classes", classesService.selectClassesById1(Long.parseLong(String.valueOf(gradeId1))));
return prefix + "/edit";
}
Edit.html
$(document).ready(function () {
//获取controller层的函数,进行默认选中
var gradeId = [[${cba}]];
var classesId = [[${abc}]];
$("#grade").val(gradeId);
$("#classes").val(classesId);
$("#grade").change(function () {//同上面一样
$.ajax({
url: ctx + "system/classes/select",
type: 'GET',
data: {
gid: $("#grade").val(),
},
success:function (data) {
$("#classes").empty();
$("#classes").append("<option value=''>请选择班级</option>");
for (var i = 0; i < data.length; i++){
$("#classes").append("<option value='" + data[i].cid + "'>" + data[i].cname + "</option>");
}
}
})
});
$("#classes").change(function () {//赋值给input输入框添加到数据库
$("#class").val($("#classes").val());
})
})
<div class="form-group">
<label class="col-sm-2 control-label is-required">学生年级:</label>
<div class="col-sm-10">
<select id="grade" class="form-control">
<option value="">请选择年级</option>
<option th:each="sc:${grade}" th:value="${sc.gid}" th:text="${sc.gname}" ></option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label is-required">学生班级:</label>
<div class="col-sm-10">
<select id="classes" class="form-control">
<option value="">请选择班级</option>
<option th:each="cl:${classes}" th:value="${cl.cid}" th:text="${cl.cname}" th:field="*{cid}"></option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input id="class" name="class" th:field="*{cid}" class="form-control" type="hidden" required>
</div>
</div>
效果图