很久没用过layui框架了,最近在修改代码时,遇到一个问题,就是怎么动态设置选中单选按钮。需求是根据后台返回的数据中的性别(0和1)设置动态选中性别单选按钮。效果图如下:

layui动态设置单选按钮选中

前端页面代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>个人资料--layui后台管理</title>
		<link rel="stylesheet" href="/layui/css/layui.css" />
		<link rel="stylesheet" href="/css/user.css" />
	</head>
	<body class="childrenBody">
		<form class="layui-form" lay-filter="form">
			<div class="user_left">
				<div class="layui-form-item">
				    <label class="layui-form-label">用户名</label>
				    <div class="layui-input-block">
				    	<input class="layui-input layui-disabled username" name="username" disabled />
				    </div>
				</div>
				<div class="layui-form-item">
				    <label class="layui-form-label">真实姓名</label>
				    <div class="layui-input-block">
				    	<input class="layui-input realName" lay-verify="required" name="name" />
				    </div>
				</div>
				<div class="layui-form-item">
				    <label class="layui-form-label">性别</label>
				    <div class="layui-input-block">
				    	<input type="radio" name="gender" value="1" title="男" />
		     			<input type="radio" name="gender" value="0" title="女" />
				    </div>
				</div>
				<div class="layui-form-item">
				    <label class="layui-form-label">手机号码</label>
				    <div class="layui-input-block">
				    	<input type="tel" class="layui-input phone" lay-verify="required|phone" name="phone" />
				    </div>
				</div>
				<div class="layui-form-item">
				    <label class="layui-form-label">出生年月</label>
				    <div class="layui-input-block">
				    	<input class="layui-input birthDate" lay-verify="required|date" name="birthDate" />
				    </div>
				</div>
				<div class="layui-form-item">
				    <label class="layui-form-label">兴趣爱好</label>
				    <div class="layui-input-block">
					    <input type="checkbox" name="like1[Java]" title="Java" />
					    <input type="checkbox" name="like1[C++]" title="C++" />
					    <input type="checkbox" name="like1[php]" title="PHP" />
				    	<input type="checkbox" name="like1[javascript]" title="Javascript" />
				    	<input type="checkbox" name="like1[jquery]" title="JQuery" />
					    <input type="checkbox" name="like1[html]" title="HTML5" />
					    <input type="checkbox" name="like1[css]" title="CSS3" />
					    <input type="checkbox" name="like1[VUE]" title="VUE" />
					    <input type="checkbox" name="like1[Layui]" title="Layui" />
					    <input type="checkbox" name="like1[EasyUI]" title="EasyUI" />
				    </div>
				</div>
				<div class="layui-form-item">
				    <label class="layui-form-label">邮箱</label>
				    <div class="layui-input-block">
				    	<input class="layui-input email" lay-verify="required|email" name="email" />
				    </div>
				</div>
				<div class="layui-form-item">
				    <label class="layui-form-label">自我评价</label>
				    <div class="layui-input-block">
				    	<textarea placeholder="请输入内容" class="layui-textarea"></textarea>
				    </div>
				</div>
			</div>
			<div class="user_right">
				<img class="layui-circle" title="更换头像" id="userFace" />
			</div>
			<div class="layui-form-item" style="margin-left:5%;">
			    <div class="layui-input-block">
			    	<a class="layui-btn" lay-submit="" lay-filter="save">立即提交</a>
					<button type="reset" class="layui-btn layui-btn-primary">重置</button>
			    </div>
			</div>
		</form>
		<script src="/layui/layui.js"></script>
		<script src="/js/userInfo.js"></script>
	</body>
</html>

后台接口/admin/getLogin返回的数据格式为

{
    "code": 200,
    "data": {
        "id": 1,
        "name": "超级管理员",
        "gender": 0,
        "username": "admin",
        "password": "123456",
        "roleId": "11111",
        "head": "/admin/20220520004040.jpg",
        "phone": "18888888888",
        "email": "heyl_163_com@163.com",
        "birthDate": "2022-09-11",
        "unlockCode": "123456",
        "lastLoginTime": "2022-10-15 03:13:09"
    }
}

userInfo.js文件的内容:

let $, form, $form;
layui.config({
	base : "/js/"
}).use(['form', 'layer', 'laydate'],function(){
	let layer = (parent.layer === undefined) ? layui.layer : parent.layer, laydate = layui.laydate, upload = layui.upload;
	$ = layui.jquery;
	form = layui.form;
	$form = $('form');
	laydate.render({
		elem: '.birthDate'
	});
	$(".realName").attr("placeholder", "请输入真实姓名");
	$(".phone").attr("placeholder", "请输入手机号码");
	$(".birthDate").attr("placeholder", "请输入出生年月");
	$(".email").attr("placeholder", "请输入邮箱");
	upload.render({
		elem: '#userFace',
		url: '/admin/upload',
		accept: 'file',
		done: function(res, index, upload) {
			$.get("/admin/getLogin", function(response) {
				$("#userFace").attr("src", response.data.head);
				layer.msg("头像修改成功");
			}, 'json');
		},
		error: function(index, upload) {
			//请求异常回调
		}
	});
	$.get("/admin/getLogin", function(response) {
		let result = response.data;
		$(".email").val(result.email);
		$(".phone").val(result.phone);
		$(".realName").val(result.name);
		$(".username").val(result.username);
		$(".birthDate").val(result.birthDate);
		$("#userFace").attr("src", result.head);
		$("input:radio[value='" + result.gender +"']").prop("checked", true);
	}, 'json');
    // 提交个人资料
    form.on('submit(save)', function() {
    	let index = layer.msg('提交中,请稍候',{
    		icon: 16,
    		shade: 0.8,
    		time: false
    	});
    	let data = form.val("form");
    	$.post("/admin/updateById", data, function(response) {
  			if(response.code === 200) {
  				setTimeout(function(){
  					layer.close(index);
  	  				layer.msg(response.message);
  		        }, 2000);
  			} else {
  				layer.alert(response.message, {
  					icon: 2
  				});
  			}
  		}, 'json');
	});
});

看代码好像没有什么问题,但是实际运行却不会选中,选择器也正确获取到了,这个问题找了很久,几番周折,最后才发现原来是忘记了重新渲染表单,将以上代码的ajax请求部分修改为以下代码即可。

$.get("/admin/getLogin", function(response) {
   let result = response.data;
   $(".email").val(result.email);
   $(".phone").val(result.phone);
   $(".realName").val(result.name);
   $(".username").val(result.username);
   $(".birthDate").val(result.birthDate);
   $("#userFace").attr("src", result.head);
   $("input:radio[value='" + result.gender +"']").prop("checked", true);
   
   form.render(); // 新增的的表单渲染代码
}, 'json');

后面尝试了很多次,发现以下几种方法均可设置单选按钮选中

$("input:radio[value='" + result.gender +"']").prop("checked", true);
$("input:radio[value='" + result.gender +"']").attr("checked", true);
$("input:radio[value='" + result.gender +"']").prop("checked", "true");
$("input:radio[value='" + result.gender +"']").attr("checked", "true");
$("input:radio[value='" + result.gender +"']").prop("checked", "checked");
$("input:radio[value='" + result.gender +"']").attr("checked", "checked");

此外,layui给我们提供了一个非常简单的方法来设置表单的值,可以通过表单元素的name属性给表单全部元素赋值

$.get("/admin/getLogin", function(response) {
   let result = response.data;
   form.val("form", {
      "name": result.name,
      "phone": result.phone,
      "email": result.email,
      "gender": result.gender,
      "username": result.username,
      "birthDate": result.birthDate
   });
}, 'json');

发表回复