Jquery Mask does not work inside another Jquery script

0

I've been breaking my head for months and nothing. I believe it to be relatively simple, but I give up that break my head. By being months of breaking my head, I am humble in asking for help, because I really give a solution to the case.

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

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script><scriptlanguage="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. Is it possible for the mask to go to all inputs?

Thank you

    
asked by anonymous 14.03.2017 / 01:47

2 answers

0

As you said a simple error, you are getting the element by the id, that is, it is treating a single element, to treat various use classes, something else, as it is using pure javascript to execute the functions, after creating a element dynamically the function will have to be run again, it looks more like this ...

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script><scriptlanguage="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>
    
14.03.2017 / 02:11
0

Opa Rogerio!

I found some errors in the Code.

The first of them is that we can only have one ID per page, ideally to use a Class for this case.

Another problem is that you are attaching the keyboard event in documnt Ready, which causes problems for Javascript to understand dynamically generated objects.

You can understand it better here link If you need to "play" more with masks, I recommend this Framework link

Follow Correct Code

<!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     

    
14.03.2017 / 02:19