I am creating my first plugin and decided to try and create a mask plugin that would use the #
character as the mask character. So if I called:
('input').mask('(###)-###-####');
The mask would become ( )- -
All #'s would be replaced by spaces so only the mask would show. I sort of skipped ahead of this and just wanted to see if as I get the keypress to work. What I wanted to do was as the user types a character, I want to put there character at the first occurrence of the # character. This is how I want it to be, the mask starts of as ( )- -
. If the user types a 3, then it should display
(3 )- -
. Next, it might be something like (35 )- -
. This goes on until the mask is complete. The below scripts is not very good and is probably not the best way to go at it, but just remember I am just trying to learn.
(function($) {
$.fn.mask = function(options) {
var
defaults = {
mask: '',
maskColor: '#c4c4c4',
inputColor: '#000000'
},
settings = $.extend({},defaults,options);
this.keypress(function(e)
{
var text = '';
var length = settings.mask.length;
for(var i = 0; i < length; i++)
{
var c = settings.mask.charCodeAt(i);
if(c != '35') //35 is the # character
{
text += settings.mask.charAt(i); /*Trying to do (342)-292-2029
for example, but after the
first character, it does
()-()-()3 instead. */
}
}
$(this).val(text);
});
}
})(jQuery);开发者_StackOverflow中文版
I played around with this a little bit here http://jsfiddle.net/gJ68n/ This could certainly be optimized, but I think it might get you moving in the right direction.
精彩评论