In the following aspx page, no matter how I call the OnClientClick="return validate()", the page will post back. The following is what I have tried and the results of each attempt:

OnClientClick="return true" ----- Successful Postback

OnClientClick="return false" ------ No Postback

OnClientClick="return validate()" ----- Successful even with bad input

OnClientClick="return validate()" ------ Successful with good 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>

Related posts

Recent Viewed