Become Wordpress Professional - Your Ultimate Wordpress Guide

Wednesday, 25 September 2013

Restrict input field to alphabets only using jQuery

Using jQuery to allow alphabets only to input fields
jQuery can be used to restrict input fields to accept alphabets only. The input field can either be a simple text field or a box where user will input something.

Where can input restriction to alphabets only can be useful?

This restriction can be useful during a form validation using jQuery where you need to make sure a user does not use symbols or other characters that you do not require.

Lets assume that we have a simple text field where we do not want any character other than small alphabets from ''a'' to ''z''. Below is the chunk of jQuery script that you can utilize to make this work:

The HTML Part:

The jQuery Part:

  $('input:text[name="sometext"]').bind('keyup blur', function(){
     $(this).val( $(this).val().replace(/[^a-z]/g,'') );

The jQuery Explanation

Here is how the workflow of the jQuery script written above works:

1) First of all the DOM checks that the document(webpage containing this script) has completed loading.

2) Then we have targeted our input field with name "sometext" and have asked jQuery to bind two functions to it that are "keyup" and "blur".

3) The "keyup" function makes sure to check that the characters being input by users are alphabets only, while the purpose of blur function is to remove unwanted characters if a users pastes something into the text directly.

4) We are using Regular expression match to check that the characters are small alphabets only.

Important Note: Make sure to link to jQuery library within the section of your webpage and paste the above jQuery script after that or in the footer otherwise it wont work.

Doing it the other way

Lets suppose that we do not want to do it via jQuery, then we can do it by passing an inline "keyup" command such as:

Simple as that, this would work fine as well.

1 comment:

Please Avoid Spamming. Comments will be moderated before they are published.