我在弹出框中创建了一个登录表单。当用户名字段留空时,将出现一条错误消息,通知用户填写空的用户名字段。作为测试,我单击登录按钮,保留用户名字段,消息按预期显示在弹出框中。但问题是弹出框立即关闭。 所以,我的问题是如何保持弹出框打开并显示错误消息?
这是我的脚本:
<!doctype html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Modal Login Window Demo</title>
<link rel="shortcut icon" href="http://designshack.net/favicon.ico">
<link rel="icon" href="http://designshack.net/favicon.ico">
<link rel="stylesheet" type="text/css" media="all" href="http://designshack.net/tutorialexamples/modal-login-jquery/style.css">
<script type="text/javascript" src="http://designshack.net/tutorialexamples/modal-login-jquery/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="http://designshack.net/tutorialexamples/modal-login-jquery/js/jquery.leanModal.min.js"></script>
</head>
<body>
<div id="w">
<div id="content">
<center><a href="#loginmodal" class="flatbtn" id="modaltrigger">Modal Login</a</center>
</div>
</div>
<div id="loginmodal" style="display:none;">
<?php
if($_POST["loginbtn"]){
if(!$_POST["username"]){
echo "<center><font color=red>please fill your username</font></center>";
}elseif(!$_POST["password"]){
echo "<center><font color=red>please fill your password</font></center>";
}
}
?>
<h1>User Login</h1>
<form method="post">
<label for="username">Username:</label>
<input type="text" name="username" id="username" class="txtfield" tabindex="1">
<label for="password">Password:</label>
<input type="password" name="password" id="password" class="txtfield" tabindex="2">
<div class="center"><input type="submit" name="loginbtn" id="loginbtn" class="flatbtn-blu hidemodal" value="Log In" tabindex="3"></div>
</form>
</div>
<script type="text/javascript">
$(function(){
$('#loginform').submit(function(e){
return false;
});
$('#modaltrigger').leanModal({ top: 110, overlay: 0.45, closeButton: ".hidemodal" });
});
</script>
</body>
</html>
最佳答案
closeButton
选项将始终导致单击相应按钮时关闭模式。查看leanModal
源代码,似乎没有任何直接的方法来操纵其事件处理回调。
因此,如果您想要做的只是在未填写字段的情况下保持表单模式打开,并让服务器端代码执行验证,您只需执行以下操作:
$('#loginform').submit(function(e){
if(!$('#username').val()) {
$('#loginmodal').show();
}
else
console.log("Enter your username");
return false;
});
现场演示 jsfiddle 。请注意,我向表单标记添加了一个 id
,并修复了 fiddle 中的一些格式错误的 HTML 标记。
关于javascript - 表单在弹出框中提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25540705/