The_Punisher 15 de abr. de 2010
E ai cara blz, pode postar o evento que vc gera essa máscara? Só pra gente ter uma idéia?
Vlw e abraço
robinsonbsilva 15 de abr. de 2010
Segue o .js
function AplicaMascara ( Mascara , elemento ) {
// Seta o elemento
var elemento = ( elemento ) ? elemento : document . getElementById ( elemento );
if ( ! elemento )
return false ;
// Método que busca um determinado caractere ou string dentro de uma Array
function in_array ( oque , onde ) {
for ( var i = 0 ; i < onde . length ; i ++ ) {
if ( oque == onde [ i ] ) {
return true ;
}
}
return false ;
}
// Informa o array com todos os caracteres que podem ser considerados caracteres de mascara
var SpecialChars = [ ':', '-', '.', '(',')', '/', ',', '_' ] ;
var oValue = elemento . value ;
var novo_valor = '' ;
for ( i = 0 ; i >< oValue . length ; i ++ ) {
// Recebe o caractere de mascara atual
var nowMask = Mascara . charAt ( i );
// Recebe o caractere do campo atual
var nowLetter = oValue . charAt ( i );
// Aplica a masca
if ( in_array ( nowMask , SpecialChars ) == true && nowLetter != nowMask ) {
novo_valor += nowMask + '' + nowLetter ;
} else {
novo_valor += nowLetter ;
}
// Remove regras duplicadas
var DuplicatedMasks = nowMask + '' + nowMask ;
while ( novo_valor . indexOf ( DuplicatedMasks ) >= 0 ) {
novo_valor = novo_valor . replace ( DuplicatedMasks , nowMask );
}
}
// Retorna o valor do elemento com seu novo valor
elemento . value = novo_valor ;
}
joao.neto 15 de abr. de 2010
Para isso eu uso Expressões Regulares
Somente Numeros < br / >
< input type = "text" name = "numeros" onkeydown = "mascara(this,soNumeros)" maxlength = "5" / >< br / >
Telefone < br / >
< input type = "text" name = "telefone" onkeydown = "mascara(this,telefone)" maxlength = "14" / >< br / >
Cep < br / >
< input type = "text" name = "cep" onkeydown = "mascara(this,cep)" maxlength = "9" / >< br / >
Cpf < br / >
< input type = "text" name = "cpf" onkeydown = "mascara(this,cpf)" maxlength = "14" / >
< script type = "text/javascript" >
function mascara ( o , f ){
v_obj = o
v_fun = f
setTimeout ( "execmascara()" , 1 )
}
function execmascara (){
v_obj . value = v_fun ( v_obj . value )
}
function soNumeros ( v ){
return v . replace ( / \ D / g , "" )
}
function telefone ( v ){
v = v . replace ( / \ D / g , "" )
v = v . replace ( /^ ( \ d \ d )( \ d ) / g , "($1) $2" )
v = v . replace ( / ( \ d { 4 })( \ d ) / , "$1-$2" )
return v
}
function cpf ( v ){
v = v . replace ( / \ D / g , "" )
v = v . replace ( / ( \ d { 3 })( \ d ) / , "$1.$2" )
v = v . replace ( / ( \ d { 3 })( \ d ) / , "$1.$2" )
v = v . replace ( / ( \ d { 3 })( \ d { 1 , 2 }) $ / , "$1-$2" )
return v
}
function cep ( v ){
v = v . replace ( / \ D / g , "" )
v = v . replace ( /^ ( \ d { 5 })( \ d ) / , "$1-$2" )
return v
}
< / script >