效果图
功能描述:页面加载时动态获取一级类别数据,根据一级类别选中的数据项动态获取二级类别的数据,并回显。
html模板
<div class="layui-inline">
<label class="layui-form-label" style="width: auto">一级类别<span style="color: red">*</span></label>
<div class="layui-input-inline">
<select id="firstCategoryId" name="firstCategoryId" lay-filter="search_firstCategory" lay-search="" >
<option value=""></option>
</select>
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label" style="width: auto">二级类别<span style="color: red">*</span></label>
<div class="layui-input-inline">
<select id="secondCategoryId" name="secondCategoryId" lay-filter="search_secondCategory" lay-search="" >
<option value=""></option>
</select>
</div>
</div>
js代码
/*
* @params formId 表单id
* @params select select标签的lay-filter的值
* @params firstCategoryId,secondCategoryId select标签id
*/
function renderCategorySelect(formId, select, firstCategoryId, secondCategoryId) {
// 一级类别选择
$(function () {
$.ajax({
async: false,
url: SSP.ctxPath + "/category/getFirstCategory",
type: 'get',
dataType: 'json',
success: function (res) {
if (res.code === 200){
var list = res.data;
$('#firstCategoryId').empty();
var s = '<option value="">请选择一级类别</option>';
$.each(list, function (index, item) {
if (item.id == firstCategoryId) {
s = s + '<option value="' + item.id + '" selected="selected">' + item.categoryName + '</option>';
} else {
s = s + '<option value="' + item.id + '">' + item.categoryName + '</option>';
}
});
$('#'+formId+' #firstCategoryId').html(s);
// 重新渲染,固定写法
form.render('select');
}
},
error: function (XMLHttpRequest) {
submit = false;
layer.alert("错误提示" + XMLHttpRequest.status + ":" + XMLHttpRequest.responseText, {icon: 0});
}
});
});
// 二级类别选择
form.on('select('+select+')', function (data) {
var firstCategoryId = data.value;
var s = '<option value="">请选择二级类别</option>';
if (firstCategoryId == ''){
$('#'+formId+' #secondCategoryId').html(s);
form.render('select');
} else {
$.ajax({
async: false,
url: SSP.ctxPath + "/consult/category/getSecondCategory",
type: 'get',
data: {firstCategoryId: firstCategoryId},
dataType: 'json',
success: function (res) {
if (res.code === 200){
var list = res.data;
$('#secondCategoryId').empty();
var s = '<option value="">请选择二级类别</option>';
$.each(list, function (index, item) {
if (item.id == secondCategoryId) {
s = s + '<option value="' + item.id + '" selected="selected">' + item.categoryName + '</option>';
} else {
s = s + '<option value="' + item.id + '">' + item.categoryName + '</option>';
}
});
$('#'+formId+' #secondCategoryId').html(s);
// 重新渲染,固定写法
form.render('select');
}
},
error: function (XMLHttpRequest) {
submit = false;
layer.alert("错误提示" + XMLHttpRequest.status + ":" + XMLHttpRequest.responseText, {icon: 0});
}
});
}
});
}