Jquery mask does not work within another Jquery script

Asked

Viewed 280 times

0

I’ve been racking my brain for months and nothing. I believe it to be relatively simple, but I give up on breaking my head. 'Cause I’ve been racking my brain for months, I’m humbled to ask for help, 'cause I really have a solution to the case.

I have a screen that the button adds more inputs. In the inputs, all were to have phone mask, but only the first has.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script language="javascript">
$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]" id="telefone" maxlength="15"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});
</script>

	<script type="text/javascript">
		/* Máscaras ER */
		function mascara(o,f){
			v_obj=o
			v_fun=f
			setTimeout("execmascara()",1)
		}
					
		function execmascara(){
			v_obj.value=v_fun(v_obj.value)
		}
			
		function mtel(v){
			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 id( el ){
			return document.getElementById( el );
		}
			
		window.onload = function(){
			id('telefone').onkeypress = function(){
				mascara( this, mtel );
			}
		}
	</script>

</head>
<body>
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]" id="telefone" maxlength="15"></div>
</div>
</body>
</html>

Please, I really do ask for help. It is possible that the mask will go to all inputs?

Thank you

2 answers

0


As you said a simple error, you’re taking the element by the id, that is to say you’re treating a single element, to treat several classes, something else, as you’re using pure javascript to perform the functions, after creating an element dynamically the function will have to be executed again, it looks like this...

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<script language="javascript">
	
  /* Máscaras ER */
		function mascara(o,f){
			v_obj=o
			v_fun=f
			setTimeout("execmascara()",1)
		}
					
		function execmascara(){
			v_obj.value=v_fun(v_obj.value)
		}
			
		function mtel(v){
			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 classe( el ){
			return document.getElementsByClassName( el );
		}
		
		function masc(){
    	var nEl = classe('telefone');
   		for(var i = 0;i < nEl.length; i++) {
      	nEl[i].onkeypress = function(){
				mascara( this, mtel );
				}
      }
		}

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]" class="telefone" maxlength="15"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
            
        }
        masc();
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});
  
</script>

</head>
<body>
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]" class="telefone" maxlength="15"></div>
</div>



<script>
	masc();
</script>

</body>
</html>

0

Opa Rogerio!

found some errors in the Code.

o First of them eh that we can only have one ID per page, the ideal is to use a Class for this case.

Another problem is that you are tying the keyboard event in documnt Ready, which creates problems for Javascript to understand Dynamic Generated Objects.

you can understand better here http://api.jquery.com/on/ If you need to "Play" more with masks, I advise this framework https://igorescobar.github.io/jQuery-Mask-Plugin/

Follows Code Corrected

<!DOCTYPE html>

$(Document). ready(Function() { var max_fields = 10; //Maximum input boxes allowed var wrapper = $(".input_fields_wrap"); //Fields wrapper var add_button = $(".add_field_button"); //Add button ID var x = 1; //initlal text box Count $(add_button). click(Function(e){ //on add input button click e. preventDefault(); if(x Remove'); //add input box } }); $(wrapper). on("click",". remove_field", Function(e){ //user click on remove text e. preventDefault(); $(this). Parent('div'). remove(); x--; }) });
<script type="text/javascript">
    /* Máscaras ER */
    function mascara(o,f){
        v_obj=o
        v_fun=f
        setTimeout("execmascara()",1)
    }

    function execmascara(){
        v_obj.value=v_fun(v_obj.value)
    }

    function mtel(v){
        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 id( el ){
        return document.getElementById( el );
    }

    $(document).on('keypress', '.telefone', function () { // Chamada para tratar o Atach d eventos
    mascara( this, mtel );
    })


</script>

Add More Fields

Browser other questions tagged

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