javascript - ASP.NET OnClientClick="return validate()" not working -
in following aspx page, no matter how call onclientclick="return validate()", page post back. following have tried , results of each attempt:
onclientclick="return true" ----- successful postback
onclientclick="return false" ------ no postback
onclientclick="return validate()" ----- successful bad input
onclientclick="return validate()" ------ successful input
onclientclick="if (!validate()) {return false;}" ----- no postback regardless of input
<!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 button to:
<asp:button id="btnsubmit" runat="server" text="login" onclick="return validate();" /> if doesn't work, use form onsubmit handler, better way go:
<form id="frmlogin" runat="server" onsubmit="return validate();">
Comments
Post a Comment