要使用layui.layer弹出新增模态框,首先准备好模态框要显示的内容:
<div id="modStaff" style="display: none;">
<div class="layui-col-lg9 layui-col-md9 layui-col-sm9 layui-col-md-offset1">
<form id="formStaff" class="layui-form" action="${ctx}/servlet/StaffServlet">
<div class="layui-form-item">
<label class="layui-form-label">编号</label>
<div class="layui-input-block">
<input type="text" name="staffNum" required lay-verify="required"
autocomplete="off" class="layui-input" readonly="readonly">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">姓名</label>
<div class="layui-input-block">
<input type="text" name="staffMC" required lay-verify="required"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item" style="text-align: center;margin-left: 18%;">
<div class="layui-btn-container">
<button type="button" class="layui-btn" lay-submit
id="btn" onclick="formSubmit();"> 保存</button>
</div>
</div>
</form>
</div>
</div>
然后加载Layui监听头部工具栏事件,当点击加号事件时,弹出新增模态框并自动生成编号:
table.on('toolbar(test)', function(obj){
var checkStatus = table.checkStatus(obj.config.id),
data = checkStatus.data; //获取选中的数据
switch(obj.event){
case 'add':
$("#formStaff").resetForm();//重置表单
var rowIndex = table.cache.test.length;//获取表格数据条数
rowIndex = Number(rowIndex - 1);//获取最后一条数据索引
if (rowIndex > -1) {
var num = table.cache.test[rowIndex].staffNum;//根据索引获取最后一条数据编号
var len = 4;
num = Number(num) + Number(1);
num = num.toString();
while(num.length < len){
num = "0" + num;
}
$("#formStaff [name='staffNum']").val(num); layer.open({
type: 1,//类型
title: '<i class="layui-icon layui-icon-add-1"> 新增员工信息</i>',
offset: ['5%','30%'],
area:['660px','560px'],//定义宽和高
shadeClose:false,//点击遮罩层关闭
content: $("#modStaff")//打开的内容
});
}
break;
}
});
代码运行效果如图:
填入员工姓名,点击保存按钮调用下面方法,提交form表单保存数据到数据库,完成新增功能。
function formSubmit(){
$("#formStaff").ajaxSubmit(function(jsonObject){
data = JSON.parse(jsonObject);
if (data.state) {
modHide();
layer.alert(data.msg, { icon : 1, title : '提示' },function(layerIndex){
layer.close(layerIndex);
table.reload();
});
} else {
layer.msg(data.msg);
}
}
}