[英]How to write a synchronous jQuery dialog for validation before submit?
这就是我想做的事情:
我有一个SUBMIT
按钮。 单击按钮后,javascript将对我的文本进行一些检查/验证(例如拼写,大写/小写)。 如果未通过检查/验证,则会弹出一个jQuery对话框,并通过两个选项进行确认:(1)无论如何提交(2)取消(返回页面并更正某些内容)。
但是,我发现代码执行所有脚本(并在中间跳过对话框的代码),因此对话框的确认代码最后执行并提交。 有没有办法让对话框的代码根据其行号执行? 非常感谢!
PS我不想使用confirm
因为我需要更大的字体。
这是<form>
:
<form name="annotation" id="annotation" method="post">
...
<input type="submit" class="btn" value="SUBMIT" id="submit">
</form>
这是脚本:
<script>
$( "form" ).submit(function( event ) {
// Perform some checking/validation
// ...
if (!valid) {
$("#dialog").dialog({width:500,
buttons: [
{
text: "Submit anyway?",
click: function() {
// Perform submission
$( this ).dialog( "close" );
}
},
{
text: "Cancel",
click: function() {
// Perform cancelation
$( this ).dialog( "close" );
}
}]
});
}
else
{
// Perform submission
}
});
</script>
而<div>
:
<div id="dialog" style="display:none"><h4>Are you sure you want to submit this?</h4></div>
例如,在我单击按钮(在valid == false
的情况下)之后,显示消息“你确定要提交这个吗?”。 然后代码提交无论如何(太快,我不能点击任何东西)。
您应该使用preventDefault()
,如下所示
<script>
$("form").submit(function(event) {
var form = event.target;
if (!valid) {
event.preventDefault() //Here you can prevent submission
$("#dialog").dialog({
width: 500,
buttons: [{
text: "Submit anyway?",
click: function() {
// Perform submission
form.submit();
$(this).dialog("close");
}
},
{
text: "Cancel",
click: function() {
// Perform cancelation
$(this).dialog("close");
}
}
]
});
} else {
// Perform submission
}
});
</script>
得到了朋友的帮助,并使用document.getElementById('').submit()
。 首先,将<input>
更改为<button>
:
<form name="annotation" id="annotation" method="post">
...
<button type="button" class="btn" onclick="submit_post()" value="SUBMIT" id="submitBtn">SUBMIT</button>
</form>
然后更改脚本:
<script>
function submit_post()
{
// Perform some checking/validation
// ...
if (!valid)
{
$("#dialog").dialog({
width:500,
buttons: [
{
text: "Submit anyway",
click: function() {
document.getElementById('annotation').submit();
$( this ).dialog( "close" );
}
},
{
text: "Cancel",
click: function() {
$( this ).dialog( "close" );
}
}
]
});
}
else
{
document.getElementById('annotation').submit();
}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.