我的应用中有一些删除表单,我想在提交之前用javascript / jQuery确认。
简单的方法是:
$('form.confirm-form').submit(function(){
return confirm('Are you sure?');
});
这会打开一个borwser-native确认框,只有在用户点击OK时才会提交表单。
对于更漂亮的东西,我认为我使用Bootstrap模式进行确认,并为此检出了Bootbox.js library。
我似乎无法使其正常工作,因为它需要回调并且不会阻止表单提交。所以我使用preventDefault
来提前停止提交表单,但现在
这是我的代码:
$('form.confirm-form').submit(function(event) {
event.preventDefault();
bootbox.confirm("Are you sure?", function(result){
return result;
});
});
如何使用此库复制本机confirm
的行为?
答案 0 :(得分:2)
试试这个FOUND HERE
$('form.confirm-form').submit(function(event) {
var currentForm = this;
event.preventDefault();
bootbox.confirm("Are you sure?", function(result){
if(result)
{
currentForm.submit()
}
});
});
答案 1 :(得分:2)
我在创建表单上遇到了这个问题,解决方案实际上非常简单,并且根本不需要任何JavaScript(如果您已经使用了JQuery和Bootstrap)。
您需要做的就是将提交按钮(按钮类型="提交")更改为触发Boostrap模式的通用按钮(按钮类型="按钮")。有关此处按钮操作的更多信息:https://stackoverflow.com/a/9643866。
然后让Boostrap模式中的按钮实际提交表单。如果您将模态HTML保留在表单中,则不需要编写一行JS。
JS Bin:https://jsbin.com/lulipubafo/edit?html,output
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<title>JS Bin</title>
</head>
<body>
<form action="/page" method="post">
<input type="text" name="first_name">
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#confirm-submit">Submit</button>
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Confirm</h2>
</div>
<div class="modal-body">
<p>Are you sure you want to submit?</p>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">Yes, Submit</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
&#13;