[英]ASP.NET OnClientClick=“return validate()” not working
In the following aspx page, no matter how I call the OnClientClick="return validate()", the page will post back. 在以下aspx页面中,无论我如何调用OnClientClick =“ return validate()”,该页面都会回发。 The following is what I have tried and the results of each attempt:
以下是我尝试过的内容以及每次尝试的结果:
OnClientClick="return true" ----- Successful Postback OnClientClick =“ return true” -----成功回发
OnClientClick="return false" ------ No Postback OnClientClick =“ return false” ------没有回发
OnClientClick="return validate()" ----- Successful even with bad input OnClientClick =“ return validate()” -----即使输入错误也可以成功
OnClientClick="return validate()" ------ Successful with good input OnClientClick =“ return validate()” ------成功,输入良好
OnClientClick="if (!validate()) {return false;}" ----- No Postback regardless of input OnClientClick =“ if(!validate()){return false;}” -----无论输入如何,均不回发
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
function validate() {
$('input[type=text]').each(function () {
if ($(this).val() === '' || $(this).val() === 'Required Field' || $(this).val() === 'Username' || $(this).val() === 'Password') {
return false;
} else {
return true;
}
});
}
$(document).ready(function () {
$('input[type=text]').focusin(function () {
$(this).removeClass('Invalid');
$(this).val('');
}),
$('input[type=text]').focusout(function () {
if ($(this).val() === '') {
$(this).removeClass('Valid');
$(this).addClass('Invalid');
$(this).val('Required Field');
} else {
$(this).addClass('Valid');
}
});
});
</script>
<title></title>
<style type="text/css">
.Invalid {
border: 2px solid red;
background-color: lightpink;
color: red;
}
.Valid {
border: 2px solid green;
background-color: lightgreen;
color: green;
}
</style>
</head>
<body>
<form id="frmLogin" runat="server">
<asp:TextBox ID="txtUser" runat="server" Text="Username"></asp:TextBox>
<asp:TextBox ID="txtPassword" runat="server" Text="Password"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Login" OnClientClick="if (!validate()) {return false;}" OnClick="btnSubmit_Click" />
</form>
</body>
</html>
You can try changing the button to: 您可以尝试将按钮更改为:
<asp:Button ID="btnSubmit" runat="server" Text="Login" OnClick="return validate();" />
If that doesn't work, use the form onsubmit handler, which is probably the better way to go: 如果那不起作用,请使用表单onsubmit处理程序,这可能是更好的方法:
<form id="frmLogin" runat="server" onsubmit="return validate();">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.