0

I am tying to validate the textboxes for achieving 'alphabets only' property in asp.net page with Jquery.

Here is the code

    <script src="//code.jquery.com/jquery-1.10.2.js"></script>

    <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
     .............codes.............

      <script type="text/javascript">
    $('.alph').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z\s]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            alert('Alphabets only');
            return false;
        }
    });
   </script>
 .............codes.............

 <asp:TextBox ID="txt_name" CssClass="alph" BorderColor="Gray" Font-Size="Large" Height="25" Width="250" runat="server"></asp:TextBox>

This code didn't work and I am sure my computer is connected to the internet to reach code.jquery.com. Help me please.

Manoj Kumar
  • 811
  • 2
  • 10
  • 22

2 Answers2

0

try this script code after Document.ready block

$(document).ready(function(){

    $('.alph').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z\s]+$");

        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            alert('Alphabets only');
            return false;
        }
    });

});

Before you can safely use jQuery you need to ensure that the page is in a state where it's ready to be manipulated. With jQuery, we accomplish this by putting our code in a function, and then passing that function to $(document).ready(). The function we pass can just be an anonymous function.

Anant Dabhi
  • 10,864
  • 3
  • 31
  • 49
0

My mistake! Since I am new to Jquery I didn't know about 'doc.ready' I corrected the code as

$(document).ready(function () {
 $('#<%=txt_name.ClientID %>').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z\s]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            alert('Alphabets only');
            return false;
        }
    });
    });

Code works perfect!

Manoj Kumar
  • 811
  • 2
  • 10
  • 22