Thursday 15 March 2012

jquery - How to perform multiple masks on demand on an Input field -



jquery - How to perform multiple masks on demand on an Input field -

iam trying perform mask on input using jquery mask plugin, need perform 2 different masks:

us###-###-###-###-###-### mask must applied if user trying type numbers @ first. (which here mean digit entry #)

but if user decided not type numerical @ first want allow him come in kind of letters or unicod character or numbers (totally character) after that

how should perform such mask?

one possible solution may using called in the jquery mask plugin's doc on-the-fly mask change, following:

html:

<input type="text" class="us" maxlength="20" autocomplete="off"/>

jquery:

$(document).ready(function(){ var options = {onkeypress: function(us){ var masks = ['caaaa-aaa-aaa-aaa-aaa-aaa', 'us000-000-000-000-000-000']; if(us.length){ mask = (us[0].match(/\d/)) ? masks[1] : masks[0]; $('.us').mask(mask, this); } $('.us').mask('aaaaa-aaa-aaa-aaa-aaa-aaa', this); }}; $('.us').mask('aaaaa-aaa-aaa-aaa-aaa-aaa', options); });

explanation:

the problem have input uses character s. although, s has different signification in plugin. according default mask legend:

s: a-z , a-z characters.

so have 2 options resolve this: utilize translation pattern, or override default options in "jquery.mask.js":

var custom_options = { bypasskeys: [8, 9, 37, 38, 39, 40], translation: { '0': {pattern: /\d/}, '9': {pattern: /\d/, optional: true}, '#': {pattern: /\d/, recursive: true}, 'a': {pattern: /[a-za-z0-9]/}, 's': {pattern: /[a-za-z]/} }; };

i take sec one! changed 's' e.g 'c'. character.

check link jsfiddle see working example.

hope it's useful!

jquery jquery-mask

No comments:

Post a Comment