问题引入:
在很多增删改查系统中会遇到Radio回显问题!
下面提供两种解决方案
一
备注: 需要回显的数据不再后台系统传输对象中,需要而外查询出进行回显处理。
比如:
下面需要回显一个用户的角色案例:
<input type="text" id="roleId" name="roleId" style="display:none;"/>
<div class="layui-form-item">
<label class="layui-form-label">角色</label>
<div class="layui-input-block show-role-container">
</div>
</div>
我们在use对象范围内定义如下:
getAllRole(function () {
//重新渲染radio
layui.form.render('radio')
});
//异步加载角色类型
function getAllRole(callback) {
$.ajax({
url: "/role/all",
type: "POST",
dataType: 'json',
success: function (result) {
var html = "";
if (result.data && result.data.length > 0) {
for (i in result.data) {
html += '<input type="radio" name="roleId" value="' + result.data[i].id + '" title="' + result.data[i].description + '" >' +
'<div class="layui-unselect layui-form-radio layui-form-radioed"><i class="layui-anim layui-icon"></i><div>' + result.data[i].name + '</div></div>';
}
$(".show-role-container").html(html);
//回调回显角色
getCurrentUserRole(callback);
}
}
});
}
处理回显的方法getCurrentUserRole
注意:下面获取的ID是需要查询出用户具体信息,所以ID可以使用隐藏域的方式获取。
function getCurrentUserRole(callback) {
//获取用户ID用来查用用户所拥有的角色
var userId = $("#userId").val();
//异步发送Ajax请求
$.ajax({
type: 'POST',
url: '/roles_user/getRoleUserByUserId',
data: {
"userId": userId
},
dataType: 'json',
success: function (result) {
if (result.code == 200) {
if (result.data) {
//回显role
$("[name=roleId]").each(function () {
if ($(this).val() == result.data.roleId) {
$(this).attr("checked", "checked");
return false;
}
})
}
if (callback) {
callback();
}
}
}
});
}
第一种情况完结:
二
数据对象从请求结果中获取并回显到前台
<div class="layui-form-item">
<label class="layui-form-label">性别</label>
<div class="layui-input-block">
<input type="radio" name="sex" id="sex" value="0" title="男">
<input type="radio" name="sex" id="sex" value="1" title="女">
</div>
</div>
js处理
//查询用户进行回显
var userId = $("#userId").val();
//回显用户性别
$.ajax({
type: "post",
url: "/user/getUserSex",
data: {
"userId": userId
},
async: true,
dataType: "json",
success: function (result) {
console.log(result.data.sex)
$("input[name=sex][value=0]").attr("checked", result.data.sex == 0 ? true : false);
$("input[name=sex][value=1]").attr("checked", result.data.sex == 1 ? true : false);
form.render(); //更新全部
}
});
以上两种情况是个人总结,有帮助欢迎点个赞,谢谢!