目前提交表单的时候只会对第一行表单能生效,新增的表单无法校验
如何对动态生成的表单进行同步校验?
<script src="{% static 'js/jquery-2.1.1.js' %}"></script>
<script src="{% static 'js/bootstrap.js' %}"></script>
<script src="{% static 'js/jquery.validate.js' %}"></script>
<script src="{% static 'js/messages_zh.min.js' %}"></script>
<script type="text/javascript" src="{% static 'js/jquery.editable-select.min.js' %}"></script>
<form class="form-horizontal" id="jsStayForm" method="post">
<table>
<tr id="tradds">
<td>
<select class="form-control m-b" name="virtual_cpu" id="virtual_cpu" autocomplete="off">
{% for cpu_i in cpu_list %}
<option value="{{ cpu_i }}">{{ cpu_i }}</option>
{% endfor %}
</select>
</td>
<td>
<select class="form-control m-b" name="virtual_mem" id="virtual_mem" autocomplete="off">
{% for mem_i in mem_list %}
<option value="{{ mem_i }}">{{ mem_i }}</option>
{% endfor %}
</select>
</td>
</table>
<button class="btn btn-primary" type="button" id="addCenterIpGrpBtn" onclick="addCenterIpGrp(this)">新增一行</button>
<button class="btn btn-primary btn-danger" id="jsStayBtn">添加虚拟机</button>
</form>
<script type="text/javascript">
##此处是进行使用插件,对下拉菜单进行可输入扩展
$('#virtual_cpu').editableSelect({
effects: 'slide'
});
$('#virtual_mem').editableSelect({
effects: 'slide'
});
### 此处对需要动态添加输入表单进行扩展
var varCount =1;
function addCenterIpGrp(obj) {
varCount++;
console.log(varCount);
html = '<tr id="tradds">\n' +
' <td>\n' +
' <select class="form-control" name="virtual_cpu" id="virtual_cpu' + varCount + '" autocomplete="off">\n' +
' {% for cpu_i in cpu_list %}\n'+
' <option value="{{ cpu_i }}">{{ cpu_i }}</option>\n'+
' {% endfor %}\n' +
' </select>\n' +
' </td>\n' +
' <td>\n' +
' <select class="form-control m-b" name="virtual_mem" id="virtual_mem' + varCount + '" autocomplete="off">\n' +
' {% for mem_i in mem_list %}\n'+
' <option value="{{ mem_i }}">{{ mem_i }}</option>\n'+
' {% endfor %}\n' +
' </select>\n' +
' </td>\n' +
'</tr>';
### 动态新增表单
var d1 = document.getElementById('tradds');
d1.insertAdjacentHTML('afterend', html);
$("#virtual_cpu" + varCount).editableSelect({
effects: 'slide'
});
$("#virtual_mem" + varCount).editableSelect({
effects: 'slide'
});
### 在此处,对动态添加的表单使用 jquery.validate 校验
$("#virtual_cpu" + varCount).rules("add", {
required: true,
digits: true,
min: 1,
max: 64,
messages: {
digits: "请输入正整数"
}
});
}
##对整体表单进行校验
$("#jsStayForm").validate({
rules:{
virtual_cpu:{
required:true,
digits:true,
min:1,
max:64,
},
virtual_mem:{
required:true,
digits:true,
min: 1,
max: 128,
},
submitHandler:function(form) {
alert('ddd');
$.ajax({
.....
});
}
});
<script>