To achieve form validation and submit the form without refreshing, we can use two useful plug-ins of jQuery - jquery validate.js and jquery form.js. The details are explained below.
1. jQuery validate.js. To put it bluntly, it means that a very noble person has written the verification of various forms for us. We don’t have to write it now. It’s so tiring every day. ,hehe.
2. jQuery form.js, "This plug-in allows you to simply upgrade forms submitted in HTML to forms submitted using AJAX technology. The main methods in the plug-in, ajaxForm and ajaxSubmit, Information can be collected from the form component to determine how to handle the form submission process. Both methods support a large number of optional parameters, allowing you to have complete control over the submission of data in the form. This allows you to submit a form using AJAX. The process couldn’t be easier!”
Please see the code example below:
Form:
<form action="@Url.Action("AddColumns","Content")" method="post" id="AddColumnsForm"> <div class="form-group js-EditCol" id="AddName"> <label class="control-label">名称</label> <input name="Name" class="form-control" required /> </div> <div class="form-group js-EditCol" id="AddRemark"> <label class="control-label">备注</label> <input name="Remark" class="form-control" /> </div> <div class="form-group js-EditCol" id="AddColumnTypeId"> <label class="control-label">类型</label> <select class="form-control" name="ColumnTypeId" id="AddColumnTypeIdSel" required> </select>//下拉列表空置验证之要项目的Value值是空的就认为是空值 </div> <input type="submit" class="btn btn-primary" value="新增栏目" /> <input type="reset" class="btn btn-default" value="清空" /> </form>
javascript:
$(document).ready(function () { $("#AddColumnsForm").validate({ submitHandler: function(form) { $(form).ajaxSubmit(); } }); });
I will strengthen it later
$(document).ready(function () { $("#AddColumnsForm").validate({ submitHandler: function(form) { $(form).ajaxSubmit({ success: function (result) { //表单提交后更新页面显示的数据 $('#TreeTable').treegrid('reload'); var d = result.split(';'); ShowMsg(d[0], d[1], d[2]); } }); } }); });
Then modify the error message display position to conform to the bootstrap style
$(document).ready(function () { $("#AddColumnsForm").validate({ errorPlacement: function (error, element) {//自定义错误信息显示操作,element是出错的input控件,error可以认为是是包含
The label of the error message
element.next('span.help-block').remove(); element.after('<span class="help-block">' + error.text() + '</span>'); element.parent().addClass("has-error"); },submitHandler: function(form) { $(form).ajaxSubmit({ success: function (result) { $('#TreeTable').treegrid('reload'); var d = result.split(';'); ShowMsg(d[0], d[1], d[2]); } }); } });
The above content introduces the jquery.validate and jquery.form plug-in combination to implement AJAX submission after verifying the form. Please forgive me for the poor writing of this article, thank you.