Home > Coding, jQuery > jQuery Plugin

jQuery Plugin

Cool, I just wrote my first jQuery plugin. For the web application I am working on I wanted to limit the input in a couple of the form fields to just letters and numbers, but I also wanted to automatically fold lower case letters to upper case. This is what I came up with:

(function($){
   $.fn.iMegAZ09 = function() {     
      return this.each ( function() {
         $(this).keypress(function(e) {
         var k;
         var charCode;
         var allow = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
         if (!e.charCode) charCode = e.which;
            else charCode = e.charCode;
         k = String.fromCharCode(charCode);
         k=k.toUpperCase();
         if (allow.indexOf(k) != -1) {
            var maxlen = $(this).attr('maxlength');
            var x = $(this).val();
            if (maxlen == -1 || x.length < maxlen) {
               $(this).val(x+k);
               }
            }
         if (e.keyCode==8) {             // backspace
            var x = $(this).val();
            x = x.substr(0,x.length-1);
            $(this).val(x);
            }
         if (e.keyCode!=9) {            // suppress all except tab
            e.preventDefault();
            }
         });
      });
   }    
})(jQuery);

To use it, just add it to the selector of an input field on the page like this:

$(‘selector’).AZ09();

OK, so it’s not perfect. It probably stops far to many non input key keystrokes and if you put the cursor in the middle of an input field (with the mouse) and start typing, the new characters get added to the end of the input regardless but hey, it is my very first plugin, gotta start somewhere.

Advertisements
Categories: Coding, jQuery
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: