Skip to content

Instantly share code, notes, and snippets.

@rafagarcia
Created November 27, 2012 14:28
Show Gist options
  • Select an option

  • Save rafagarcia/4154505 to your computer and use it in GitHub Desktop.

Select an option

Save rafagarcia/4154505 to your computer and use it in GitHub Desktop.
Jquery mask plugin for input fields
<div class="maskedInputContainer">
<input type="text" class="tipo" maxlength="16" id="numero" name="numero" data-mask />
</div>
<p class="visualizeDemo">El valor escrito es: <span id="valor"></span></p>
/*
Jquery Mask Plugin
Developed by Denis Ciccale, Ilias Moreno and Rafa García
Version 1.0
27/11/2012
*/
(function () {
$.fn.mask = function (options) {
var defaults = {
charLength: 16,
stopAt: 12,
maskChar: '\u25CF'
};
var settings = $.extend({}, defaults, options);
return this.each(function () {
var $input = $(this),
totalValue,
originalValue = '';
$('<input type="text" class="tipo_mask" style="height: ' + $input.css('height') + '" maxlength="' + settings.charLength + '" />')
.insertAfter($input)
.keypress(function (e) {
e.preventDefault();
var keyPress = e.which,
valueClicked = String.fromCharCode(keyPress),
length = this.value.length,
realInputVal = $input.val(),
val = '';
if (length < settings.charLength) {
if (length < settings.stopAt + 1) {
for(i = 0; i < length; i++) {
val += settings.maskChar;
}
} else {
val = this.value;
}
this.value = val + valueClicked;
realInputVal += valueClicked;
$input.val(realInputVal) ;
$('#valor').text(realInputVal); // For demo purpose only.
}
})
.keyup(function (e) {
if(e.which === 8 || e.which === 46) { //Backspace or Supr clicked
$input.val('');
this.value = '';
}
})
.blur(function () {
// fires form validation if needed
$input.focus().blur();
});
});
};
}());
$(function () {
$('[data-mask]').mask();
});
.maskedInputContainer {
margin: 10px;
}
.visualizeDemo {
margin: 0 0 0 12px;
}
.tipo {
background: none repeat scroll 0 0 #FFFFFF;
border: 1px solid #AAAAAA !important;
border-radius: 4px 4px 4px 4px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2) inset;
color: #555555;
font-size: 14px;
outline: medium none;
padding: 0 3px;
height: 20px;
}
.tipo_mask {
background: white;
outline: none;
font-size: 14px;
color: #555;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-moz-box-shadow: inset 0 1px 4px rgba(0,0,0,.2);
-webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, .2);
box-shadow: inset 0 1px 4px rgba(0, 0, 0, .2);
padding: 0 2px;
border: 0;
margin: 1px 3px 3px 12px;
position: absolute;
left: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment