[英]ASP.NET OnClientClick=“return validate()” not working
在以下aspx頁面中,無論我如何調用OnClientClick =“ return validate()”,該頁面都會回發。 以下是我嘗試過的內容以及每次嘗試的結果:
OnClientClick =“ return true” -----成功回發
OnClientClick =“ return false” ------沒有回發
OnClientClick =“ return validate()” -----即使輸入錯誤也可以成功
OnClientClick =“ return validate()” ------成功,輸入良好
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>
您可以嘗試將按鈕更改為:
<asp:Button ID="btnSubmit" runat="server" Text="Login" OnClick="return validate();" />
如果那不起作用,請使用表單onsubmit處理程序,這可能是更好的方法:
<form id="frmLogin" runat="server" onsubmit="return validate();">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.