简体   繁体   中英

Check if TextBox is empty using JQuery, and prevent postback if so

How can I check if an asp TextBox is empty on Button click using JQuery, and prevent a postback if so?
It would also be helpful to show an alert dialog asking the user to enter something if it is empty.

So far I have:

<asp:TextBox ID="txtInput" runat="server" />
<asp:Button ID="btnOK" Text="OK" onClientClick="return checkInput();" runat="server" />

I know the JQuery function should return a true or false, but I don't know how to set the function up or if it should go inside $(document).ready(function () {}); or not.

If you are doing this in Asp.Net I would consider using MVC and its built in validation capabilities instead of creating your own.

You should also add server side validation, but you can leverage the built in MVC client side validators as well

Here's a link with info on how to do it. http://www.jacopretorius.net/2011/01/client-side-validation-in-mvc-3.html

Yes you can, just put the validate of your textbox into a function:

    <script>
        function CheckForm() {
            if ($('#<%=txtInput.ClientID %>').val() == "") {
                alert('Please input');
                return false;
            }
            return true;
        }
    </script>

    <asp:TextBox runat="server" ID="txtInput"></asp:TextBox>
    <asp:Button runat="server" Text="submit" ID="btnSubmit" OnClientClick="return CheckForm()" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM