Reputation: 2173
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.
Upvotes: 1
Views: 6392
Reputation: 68
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()" />
Upvotes: 1
Reputation: 39268
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
Upvotes: 1