版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zero_295813128/article/details/52692277
今天想在弹出的模态框中清空bootstrap的样式信息。比如下图
这是添加的模态框,每次添加的时候想还原modal,也就是重置表单,让验证信息都去掉,看到官网上有个例子说
Resetting Form When Showing the Modal
If you want to reset all the fields in form whenever the modal is shown, the resetForm()
method will help you:
$('#loginModal').on('show.bs.modal', function() {
$('#loginForm').bootstrapValidator('resetForm', true);
});
用resetForm清空即可,但是发现模态框弹出的时候,信息怎么也清空不了。后来我改成shown就能清空。但是界面上的信息已经展示才清空体验很差。但是官网的例子再次点击添加的时候,信息是可以清空的。后来我各种搜索解决方案。在stackoverflow上找到一个结果
http://stackoverflow.com/questions/26670478/bootstrap-validator-resetform
上面说的是你在boostrapValidator验证初始化的时候其实他
By default, the plugin will not initialize the fields which are disabled, hidden, or not visible.
不会初始化 disabled hidde 和 not visible的
在代码中是这样的。
excluded:[":disabled",":hidden",":not(:visible)"]
所以stackoverflow上就把这个默认值改了。我的代码如下
function bootstrapValidator(target, o) {
$(target).bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: o.fields,
excluded: [':disabled']
}
).on('success.form.bv', function (e) {
if (o.beforePost && !o.beforePost()) {
return false;
}
e.preventDefault();
var $form = $(e.target);
var nameArr = [];
var data = $form.serialize();
var $chks = $(this).find(":checkbox:not(:checked)");
var uncks = "";
$chks.each(function () {
var chkName = $(this).attr("name");
if ($.inArray(chkName, nameArr) == -1 && $form.find(":checkbox[name='" + chkName + "']:checked").length == 0) {
nameArr.push(chkName);
uncks += "&" + chkName + "=" + ($(this).val()=='on'?0:$(this).val());
}
});
if(o.datafun){
data=data+ (o.datafun()==undefined?"":o.datafun());
}
//操作名
var operServiceName = $form.parent(".modal-body").parent(".modal-content").find(".modal-header").find(".modal-title").text();
//$(target+" #singlebutton").button('loading');
$form.find("button").button('loading');
$.post(o.url, data + uncks + "&operServiceName=" + encodeURI(operServiceName), function (result) {
o.fncallback(result);
if(o.resetform!=undefined){
if(o.resetform){
$form.bootstrapValidator('resetForm', true);
$form[0].reset();
}
}else{
$form.bootstrapValidator('resetForm', true);
$form[0].reset();
}
}, 'json');
$form.find("button").button('reset');
//$(target+" #singlebutton").button('reset');
});
}
默认只排除:disabled,这样就能使用resetForm清空数据了,但是还想弹出添加form的时候,把一些表单数据重置,我就用了下面的代码
$('#headlineAddDiv').on('show.bs.modal', function() {
$('#headlineAddForm').bootstrapValidator('resetForm', true);
$('#headlineAddForm')[0].reset();
});
$('#headlineModifyDiv').on('show.bs.modal', function() {
$('#headlineModifyForm').bootstrapValidator('resetForm', false);
});
在添加的时候清空验证和数据,以及重置表单。
但是在弹出编辑表单的时候,我发现他清空了验证还把数据也清空了,在添加的时候清空是正常的,在编辑的时候清空验证还清空了数据就不正常了,这时候就需要使用第二个参数,将true改为false,false将只清空验证信息。有时候我们在添加的时候隐藏域中放入了一些值,这样的值我们不想被清空,我试了一下,发现这样的值是不会清空的,所以就不用担心这个问题了。