Telephone and CPF masks in Textfield

Asked

Viewed 6,560 times

2

How can I put masks for phone and CPF on text_field?

In app/views/layouts/application:

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.maskedinput.js"></script>

 <%= stylesheet_link_tag :all%>
 <%= javascript_include_tag :application %>
 <%= csrf_meta_tag %>

In app/Assets/javascript:

$(document).ready(function(){
  $(.tel_celular).mask("(99) 99999-9999");
});

In the form scholarship:

<%= f.text_field :tel_celular, class: "form-control", class: "span2", id: 'tel_celular' %>

But don’t carry the mask.

  • I think the problem is the selector, the quotation marks are missing $('.tel_celular'). The input has the class tel_celular?

  • Yes. You cannot work with existing class names ?

  • Well is one of the items of the scholarship class better saying.

  • I think you’re using the wrong function, don’t you? There should be some on_keypress call or something like that?!

  • What do you mean ? It’s because I’m learning to work with Rails, and some things I’m not dealing with properly.

  • the correct is not: $(.tel_celular).mask("(99) 99999-9999"); , is: $('.tel_celular').mask("(99) 99999-9999");the class is passed in string format, the same way you did to pass the mask.

  • There are 3 clear errors there: the first is that you did not quote the element .tel_celular, the second is that you created two "class", form-control and span2, which will have a conflict between the two: the correct would be class: "form-control span2", the third, and that you are treating id: 'tel_celular' as a class element, but actually by the model it suggests id, in javascript, id should be treated like this: '#tel_celular'.

  • 3

    Possible duplicate of Phone Mask Using jQuery Mask Plugin

  • In addition to possible duplicate, you need to observe what your problem is and provide the most suitable information for resolution, for example, you posted the language code that is generating the HTML of the page while your problem involves masks and jQuery, the ideal was for you to post only the HTML generated and even add a tag to the ruby in the question...

Show 4 more comments

4 answers

2

You can use the following plugin: Jquery Mask Plugin. I always use it and cater to my needs.

But there are some things you need to do.

First: Make sure that you are calling the Javascript function on the page where the input to which the filter will be applied is located.

<script type="text/javascript" charset="utf-8"> 
    $('.js_telefone').mask('(99) 99999-9999');
</script>

According to: If you are going to apply class based input you should use as described above, if it is based on replace "." with "#":

<script type="text/javascript" charset="utf-8"> 
    $('#js_telefone').mask('(99) 99999-9999');
</script>

Third: Go to the imput where the filter will be applied and declare the class. In the case of this example it will be 'js_phone':

<input type="text" class="jstelefone">

Note: Remember to import the plugin script from the page.

I hope I’ve helped.

1

Good night ,

<script type="text/javascript"> // Mascaras 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 id( el ){
	return document.getElementById( el );
}

// aqui começa as mascaras 

function mtel(v){ //MASCARA PARA TELEFONE

    v=v.replace(/\D/g,"");             //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/g,"($1) $2"); //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d)(\d{4})$/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígitos
    return v;
}


function mcpf(v){  //MASCARA PARA CPF

    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v;
}

function mcnpj(v){  //MASCARA PARA CNPJ

    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
	
	 v=v.replace(/(\d{2})(\d)/,"$1.$2")
	 v=v.replace(/(\d{3})(\d)/,"$1.$2")
     v=v.replace(/(\d{3})(\d)/,"$1/$2")       	 
     v=v.replace(/(\d)(\d{2})$/,"$1-$2");    //Coloca o . antes dos últimos 3 dígitos, e antes do verificador 
    return v;
}

function mie(v){  //MASCARA PARA CNPJ

    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito      	 
     v=v.replace(/(\d{3})(\d)/,"$1.$2")
	  v=v.replace(/(\d{3})(\d)/,"$1.$2")
	  v=v.replace(/(\d{3})(\d)/,"$1.$2")
    return v;
}


function mrg(v){  //MASCARA PARA RG

    //  v=v.replace( /\s/g, '' );                  //Remove tudo o que não é dígito
	//	v=v.replace(/(\d)(\d{7})$/,"$1.$2");   	 //Coloca o . antes dos últimos 3 dígitos, e antes do verificador
    //  v=v.replace(/(\d)(\d{4})$/,"$1.$2");    //Coloca o . antes dos últimos 3 dígitos, e antes do verificador
    //  v=v.replace(/(\d)(\d)$/,"$1-$2");       //Coloca o - antes do último dígito
		
	v=v.replace(/(\d{2})(\d)/,"$1.$2")       //Coloca um ponto entre o segundo e o terceiro dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")     
	v=v.replace(/(\d{5})(\d)/,"$1.$2")     
	v=v.replace(/(\d{9})(\d)/,"$1-$2")       
    return v;
}

function mcep(v){  //MASCARA PARA CEP

    v=v.replace(/\D/g,"")                      //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2")         //Esse é tão fácil que não merece explicações
    return v;
}

function mcartao(v){ //MASCARA PARA CARTAO

    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{4})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{4})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
	v=v.replace(/(\d{4})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
	v=v.replace(/(\d{4})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    return v;
}

function mdata(v){ // MASCARA PARA DATA 

    v=v.replace(/\D/g,"");                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{2})(\d)/,"$1/$2");
    v=v.replace(/(\d{2})(\d)/,"$1/$2");
    return v;
}

function mvalor(v){  //MASCARA PARA VALOR EM $$

    v=v.replace(/\D/g,"");//Remove tudo o que não é dígito
    v=v.replace(/(\d)(\d{8})$/,"$1.$2");//coloca o ponto dos milhões
    v=v.replace(/(\d)(\d{5})$/,"$1.$2");//coloca o ponto dos milhares
 
    v=v.replace(/(\d)(\d{2})$/,"$1,$2");//coloca a virgula antes dos 2 últimos dígitos
    return v;
}

function mvalor(v){  //MASCARA PARA VALOR EM $$

    v=v.replace(/\D/g,"");//Remove tudo o que não é dígito
    v=v.replace(/(\d)(\d{8})$/,"$1.$2");//coloca o ponto dos milhões
    v=v.replace(/(\d)(\d{5})$/,"$1.$2");//coloca o ponto dos milhares
 
    v=v.replace(/(\d)(\d{2})$/,"$1,$2");//coloca a virgula antes dos 2 últimos dígitos
    return v;
}

function memail(v){

		v=v.replace( /\s/g, '' );
		return v;
}

window.onload = function(){ // FUNCAO QUE É ACIONADO AO CARREGAR A PAGINA ( WINDOW.ONLOAD )

	id('txtCel').onkeyup = function(){ //ATRIBUI O CAMPO COM ID txtCel A MASCARA DE TELEFONE
		mascara( this, mtel );
	}
	
	id('txtFixo').onkeyup = function(){ //ATRIBUI O CAMPO COM ID txtFixo A MASCARA DE TELEFONE
		mascara( this, mtel );
	}
	
	id('txtComercial').onkeyup = function(){ //ATRIBUI O CAMPO COM ID txtComercial A MASCARA DE TELEFONE
		mascara( this, mtel );
	}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="row">
					<div class="col-md-6">
						<div class="form-group">
							<label class="control-label col-md-3">Celular</label>
								<div class="col-md-4">
									<input type="tel" class="form-control" id="txtCel" name="txtCel" value="<?php echo $_POST['txtCel'];?>" maxlength="15" >
								</div>
						</div>
					</div>
													
					<div class="col-md-6">
						<div class="form-group">
							<label class="control-label col-md-3">Telefone fixo</label>
								<div class="col-md-4">
									<input type="text" id="txtFixo" name="txtFixo" class="form-control" value="<?php echo $_POST['txtFixo'];?>" maxlength="15" >
								</div>
						</div>
					</div>
							
					<div class="col-md-6">
						<div class="form-group">
							<label class="control-label col-md-3">Telefone Comercial</label>
								<div class="col-md-4">
									<input type="tel" class="form-control" id="txtComercial" name="txtComercial" value="<?php echo $_POST['txtComercial'];?>" maxlength="15">
								</div>
						</div>
					</div>
				</div><!--::: ROW :: -->

Follow test file working.

https://mega.nz/#! 3pc1ADTJ! xpX-qug03hCbJJ5UhQ1gqhc2JkP7E1MpKRMIYkXTjxw

Anything , posta ae.

  • A lot. I found that only lacked the size limiter or here did not work, I think the Regex has to limit the size if you update the answer and I give a UP

0

It is possible to use optional characters

 $('.tel_celular').mask('(99) 9999-9999?9').focusout(function() {
      var phone, element;
      element = $(this);
      element.unmask();
      phone = element.val().replace(/\D/g, '');
      if( phone.substring(0, 1) === '0' ) {
           element.mask("9999-999-9999");
      } else if (phone.length > 10) {
           element.mask("(99) 99999-999?9");
      } else {
           element.mask("(99) 9999-9999?9");
      }
 }).trigger('focusout');

-1

When using Jquery for classes start with dot

   $(.tel_celular).mask("(99) 99999-9999");

When returning according to id, use #

   $(#tel_celular).mask("(99) 99999-9999");

In this case, the class was declared tel_celular instead of span2 ex.:

   <%= f.text_field :tel_celular, class: "form-control", class: "tel_celular", id: 'tel_celular' %>

If you use this span2 class for phones, just change it in javascript to:

    $(document).ready(function(){
        $(.span2).mask("(99) 99999-9999");
    });
  • Unfortunately it didn’t work. Can’t load the masks inside text_field.

  • I don’t know what else I can do to make these masks appear.

  • @Fernanda have you linked the jquery Mask file to your project? The other functions of jquery are working?

  • Well I installed the Gem jQuery Mask in the Gemfile, put the call in the application in the path: app view layout so <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.maskedinput.js"/></script> and in the applicatio.js this: $(Document). ready(Function(){ $("#tel"). Mask("(99)99999-9999"); }); e in the view form : <%= f.text_field :tel_celular, class: "form-control", class: "tel", id: "tel" %> modified the calls, instead of tel_celular to tel to see if it changed, but still nothing.

  • I’m stuck with this part of the system.

  • @Fernanda complemented with some information in the answer above, can check?

  • Answering one of your questions above in my layout is tagged: <%= javascript_include_tag :application %>.

  • Unfortunately it didn’t work :( I tried with the options you said, I downloaded the file in git, I switched to inputmask to test, but nothing, I can’t understand why you don’t pull the mask.

  • I’m also starting to unravel the features of Ruby on Rails. I don’t know if it’s because I’m using version 3.2.13 of Rails.

  • Did the alert work ? Alert("Document ready");

  • @Fernanda Rails does not interfere in anything with the issue of masks, this is a question only of jQuery and the plugin you are using. Check your browser for any Javascript errors, usually by pressing the key F12 and the option Console, If you have any error put here please.

  • @wcj, the element must be passed as string.

  • @Ivanferrer and what does that have to do?

  • @wcj, what it has to do is that you are not passing as string the class name: $(.tel_celular) change to $('.tel_celular'), besides, you have to see if it’s a class or if it’s id, id: $('#tel_celular') <> class: $('.tel_celular')

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.