layui表单动态赋值与取值,官网给的demo表单赋值部分可能有点不太好用,相信大家都有点不太明白怎么赋值的,以下内容可供大家参考!

点击下方取值按钮后即可在控制台看到代码初始为表单赋值的数据

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>layui表单动态赋值与取值</title>
		<link rel="stylesheet" type="text/css" href="https://cdn.staticfile.org/layui/2.6.8/css/layui.css" />
		<script src="https://cdn.staticfile.org/layui/2.6.8/layui.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<style type="text/css">
		#wrap {
			padding: 20px;
		}
	</style>
	<body>
		<div id="wrap">
			<h1>layui表单动态赋值与取值</h1>
			<div class="layui-form" lay-filter="formTest">
				<div class="layui-form-item">
					<label class="layui-form-label">输入框</label>
					<div class="layui-input-block">
						<input type="text" name="username" placeholder="请输入" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">下拉选择框</label>
					<div class="layui-input-block">
						<select name="selectType" lay-filter="aihao" lay-search placeholder="支持搜索">
							<option value="0">HTML</option>
							<option value="1">CSS</option>
							<option value="2">JavaScript</option>
						</select>
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">复选框</label>
					<div class="layui-input-block">
						<input type="checkbox" name="JavaScript" title="JavaScript">
						<input type="checkbox" name="java" title="java">
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">开关</label>
					<div class="layui-input-block">
						<input type="checkbox" name="openSwitch" lay-skin="switch">
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">单选框</label>
					<div class="layui-input-block">
						<input type="radio" name="sex" value="0" title="">
						<input type="radio" name="sex" value="1" title="">
					</div>
				</div>
				<div class="layui-form-item layui-form-text">
					<label class="layui-form-label">文本框</label>
					<div class="layui-input-block">
						<textarea placeholder="请输入内容" name="desc" class="layui-textarea"></textarea>
					</div>
				</div>
				<button type="button" class="layui-btn layui-btn-radius" id="getDatas">取值</button>
			</div>
		</div>
		<script type="text/javascript">
			layui.use(['form'], function() {
				let form = layui.form;
				//为表单赋值
				form.val("formTest", {
					"username": "程序猿", //输入框
					"selectType": 2, //下拉框
					"JavaScript": true, //复选框
					"openSwitch": true, //开关
					"sex": 1, //单选按钮
					"desc": "我爱layui", //文本框
				});
				//form.render()
				//表单取值
				document.getElementById("getDatas").addEventListener("click", function() {
					var formObj = form.val("formTest");
					console.log(formObj)
				});
			});
		</script>
	</body>
</html>

在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐