一、需求
二、实现
<div style="margin-bottom: 55px">
<form action="" method="post" enctype="multipart/form-data" id="reportForm" name="sjf" style="margin-left: 25px;margin-bottom: 50px;">
<table id="tableContent">
<tbody>
{foreach $list ke=>va}
<tr id="line-1" class="layui-form layui-row layui-col-space16 tr-line">
<td class="layui-form">
<select name="selectkey[]" class="tr-select" style="width:186px;display:inline" oninput="handleSelectChange(event)">
<option value="" >请选择</option>
{foreach $selectList k=>v}
<option value="{$v['key']}" {if $ke == $v['key']} selected="selected" {/if} >{$k}</option>
{/foreach}
</select>
</td>
<td class="td_Item">
<input type="text" name="selectval[]" class="stepName" autocomplete="off" value="{$va}" oninput="handleInputChange(event)">
</td>
<td class="td_Oper" style="cursor: pointer;"><i class="layui-icon layui-icon-close" onclick="remove_line(this);"></i> </td>
<td class="td_Oper" style="cursor: pointer;"><i class="layui-icon layui-icon-addition" onclick="add_line(this);"></i> </td>
</tr>
{/foreach}
</tbody>
</table>
<input type="hidden" name="immongoid" class="stepName" autocomplete="off" value="{$val['MongoID']}">
<script type="text/javascript">
//添加新记录
function add_line(index) {
//克隆上一行
$("#tableContent tbody tr:last-child").clone().appendTo("#tableContent tbody");
//将行尾克隆的值清空
$("#tableContent tbody tr:last-child").find(":input").val('');
$("#tableContent tbody tr:last-child").find("input").css('border-color','#468')
}
//删除选择记录
function remove_line(index) {
var keyindex = $("#tableContent tbody tr").index();
if (keyindex > 0) {
console.log($(index).parent().parent())
$(index).parent().parent().remove();
} else {
layer.msg('第一行不能删除')
return false;
}
}
function closeFun(){
$('.stepName').each(function(){
$(this).css('border-color','#468')
})
$('.tr-select').each(function(){
$(this).css('border-color','#468')
})
}
function handleInputChange(e){
$('.stepName').each(function(){
if($(this)[0] == e.target){
$(this).css('border-color','#468')
}
})
}
function handleSelectChange(e){
$('.tr-select').each(function(){
if($(this)[0] == e.target){
$(this).css('border-color','#468')
}
})
}
# 表单验证并保存,一行中有未填写内容时input框标红并阻止提交
function submitClick(inp){
let isCheck = true;
$('.tr-line').each(function(index,key){
if($(this).find('select')){
if($(this).find('select option:selected').text() == '请选择'){
$(this).find('select').css('border-color','red');
isCheck = false
}else{
$(this).css('border-color','#468')
}
if($(this).find('input').val() == ''){
$(this).find('input').css('border-color','red');
isCheck = false
}else{
$(this).css('border-color','#468')
}
}
})
if(!isCheck){
return
}
$.ajax({
url:'/ajax/test',
data:$("#reportForm").serialize(),
async:false,
type:'post',
dataType:'json',
success:function(data){
layer.msg('保存成功')
}
});
}
</script>
</form>
<div class="want_box-bottom1" style="margin-left: 32px;">
<span><input type="submit" value="保存" onclick="submitClick(this)" class="gray-but"></span>
</div>
{/if}
</div>