Tuesday, August 9, 2011

jQuery wildcard selector, and input mask on Rails 3

For my big project I wanted to be able to load one jQuery partial in my view (to have content_for a :jQuery_ui yield), and find elements with IDs containing certain things (Like *phone*). I searched high and low and finally came across comments in a blog somewhere (the link is long gone). *= works as a wildcard, surrounding whatever you put in with wildcards. This is significantly better than having to install a regexp plugin for jQuery (and all the overhead that comes with it)

I used masked-input-plugin, a simple jQuery plugin. My form contains something like:

<%= f.text_field :phone_number %>
(outputs [model_name]_phone_number)
and later

<%= f.text_field :postal_code %>
(outputs [model_name]_postal_code)

and this code applies the masks accordingly:

//Select anything with "phone" in it, and apply mask. '9's mean numbers only.
  $j('input[id*="phone"]').each (function(){
      $j(this).mask("(999) 999-9999");
    }
  );
  //Select anything with "postal_code" and apply mask
  //The '?' means anything following the '?' is optional.  In this case, the +4 on 
  //the postal code is optional.  Even though this is called postal code,
  //it's really only for a zip, since Canada (for instance) uses alphanumeric codes,
  //which will be disallowed in the input.
  $j('input[id*="postal_code"]').each (function(){
      $j(this).mask("99999?-9999");
    }
  );
  //Select anything with "max" (for instance my_max_users) and apply mask.
  $j('input[id*="max"]').each (function(){
      $j(this).mask("9?99999", {placeholder:""});
    }
  );

Any non-numeric input is ignored with the 9s, another sanity checking bonus. Now, as long as the user has javascript turned on, I can expect MOST of my input to be sanely formatted.

This was a very exciting find, and is really here in case I need to figure it out again in the future. Hopefully someone finds it who's trying to do the same thing -- that's why the title is so verbose.

~Nic

1 comment:

Kelly said...

THANK YOU so much for this tip. I used for Grails project. It will save me a ton of time!