简体   繁体   English

使用JQuery检查TextBox是否为空,如果是,则防止回发

[英]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? 如何使用JQuery在Button单击时检查asp文本框是否为空,如果是,则防止回发?
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 () {}); 我知道JQuery函数应该返回true或false,但是我不知道如何设置该函数或是否应该将其放入$(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. 如果您在Asp.Net中进行此操作,我会考虑使用MVC及其内置的验证功能,而不是创建自己的验证功能。

You should also add server side validation, but you can leverage the built in MVC client side validators as well 您还应该添加服务器端验证,但是您也可以利用内置的MVC客户端验证器

Here's a link with info on how to do it. 这是有关如何执行此操作的信息的链接。 http://www.jacopretorius.net/2011/01/client-side-validation-in-mvc-3.html 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()" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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