Maskmoney does not work on duplicate input via javascript

Asked

Viewed 106 times

0

Good night, you guys,

I have a code that uses maskmoney.

I’m using cloneNode to copy a div, it works, but the input I use maskmoney does not work in the copied fields.

Someone can help ?

//script mask money
        $(document).ready(function(){
              $("#valor").maskMoney({showSymbol:true, symbol:"R$", decimal:".", thousands:""});
        });

Here is the clone function

<script>
    function duplicarCampos(){
    var clone = document.getElementById('origem').cloneNode(true);
    var destino = document.getElementById('destino');
    destino.appendChild (clone);
    
    
    var camposClonados = clone.getElementsByTagName('input');
        
    
    for(i=0; i<camposClonados.length;i++){
        camposClonados[i].value = '';
    }
    
    
    
}

        function removerCampos(id){
    var node1 = document.getElementById('destino');
    node1.removeChild(node1.childNodes[0]);
}
        

Here is the input I use maskmoney

        <input type="text" name="valor[]" id="valor" style="text-align:center; width: 20%"/>    
  • clone an element with maskMoney will not make the cloned element behave the same, it is necessary to apply the maskMoney to the new element

2 answers

0

Ricardo,

Thank you so much for the help, that’s how you told me the field cloned and worked the right maskmoney, but I have more fields that are cloned in this function and with that clon all the div that has id="origin". When I change var clone = Document.getElementById('value'). cloneNode(true); to var clone = Document.getElementById('origin'). cloneNode(true); to copy all fields, maskmoney stops working again.

Follow all the code so you can see if you can help me.

I also did not use the button to clone because the button on my form makes Ubmit on it, I don’t know if it is a problem.

jQuery

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pagina</title>
<link rel="stylesheet" href="/sistema/css/geralincluir.css">
<style>
.card-form {
  width: 900px;

}
.card-form .form-body .row {

  justify-content: flex-start;

}
.card-form .form-footer button {
  width: 120px;

}
    


</style>


<script src="js/jquery.js"></script>
<script src="js/custom.js"></script>
<script src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/jquery.maskMoney.js" ></script>
<link rel="stylesheet" href="js/jquery-ui.css" />


  

<script type="text/javascript">
    
    



//script combo empresa/filial
    $(document).ready(function(){
        $('#empresa').change(function(){
        $('#filial').load('filial.php?empresa='+$('#empresa').val() );
          });
        });

//script enter não enviar form
$(document).ready(function () {
    $('input').keypress(function (e) {
        var code = null;
        code = (e.keyCode ? e.keyCode : e.which);                
        return (code == 13) ? false : true;
   });
});
    

    
</script>
    
    <script>

    function duplicarCampos(){
    var clone = document.getElementById('origem').cloneNode(true);
    var destino = document.getElementById('destino');
    destino.appendChild (clone);
    
    
    var camposClonados = clone.getElementsByTagName('input');
        
    
    for(i=0; i<camposClonados.length;i++){
        camposClonados[i].value = '';
    }
    
    
    
}

function removerCampos(id){
    var node1 = document.getElementById('destino');
    node1.removeChild(node1.childNodes[0]);
}
        

    </script>




</head>

<body bgcolor="#F5F5F5">
<span class="notprint">
<?php 

    include "menu.php"; 

?>
</span>


<br />

<div class="card-form">
   <form action="teste.php" method="post" enctype="multipart/form-data">
    <div class="form-title">DOCUMENTO ORIGINAL</div>
    <div class="form-body">
     
     
      
      
      
      
    </div>
    <div class="form-subtitle">RATEIO</div>
    
    <div class="form-body" id="origem">
        <div class="row" >
          
          <select name="empresa[]" class="select" id="empresa" style="width: 30%">
        <option value='00'>Selecione Empresa</option>
        <?php
            $result = mysqli_query(...);
        while($row = mysqli_fetch_array($result) ){
            echo "<option value='".$row['id']."'>".$row['NomeEmpresa']."</option>";
        }
    ?>
</select>
          <select name="filial[]" id="filial" class="select" style="width: 30%">
        <option value="0">Escolha uma filial</option>
    </select>
          <input type="text" name="valor[]" id="valor" style="text-align:center; width: 20%"/>  
            <img  src="img/add.png" width="20px" height="20px" style="cursor: pointer;" onclick="duplicarCampos();">
            <img  src="img/del.png" width="20px" height="20px" style="cursor: pointer;" onclick="removerCampos(this);"> 
    </div>
            
         
      </div>
        <div id="destino">
    </div>
        
    
    <div class="rule"></div>
    <br />
    
    <div class="form-footer" align="center">
    
     
      <button><i class="fas fa-plus"></i>&nbsp;Inserir</button>
      
    </div>
  </form>
</div>

</body>
</html>
  • Rubens only use the answer field if you are going to answer the question, add a comment, or edit the question and put those details there

  • see my answer, I edited a second scrip cloning the div

  • Dude you’re a genius, thank you very much and sorry for the wrong way to do the reply, it’s my first time here.

  • While I’m at it, I have another problem with this code that I posted in another question, if it’s not too much to abuse your genius and give me a hand as well. The following link: https://answall.com/questions/504047/jquery-onchange-function-nao-funciona-em-input-dinamico

  • no problem, soon get used to the OS, and if the answer helped you, do not forget to accept the answer :)

0


When creating a new element, it is necessary to associate the events, and the maskMoney also, so after cloning and adding the DOM, just use to do this.

In the example below, I put the association of maskMoney in a Function to be called multiple times, I also removed the ID (could assign a random or sequential as well) to avoid having more than one element with the same ID.

$("#clonar").click(function() { duplicarCampos(); });

aplicarMaskMoney($("#valor"));

// function para aplicar o maskMoney
function aplicarMaskMoney(elemento) {
    elemento.maskMoney({showSymbol:true, symbol:"R$", decimal:".", thousands:""});
}

function duplicarCampos(){
    var clone = document.getElementById('valor').cloneNode(true);
    
    // para evitar mais de um elemento com o mesmo ID e "zera" o valor
    clone.removeAttribute("id");
    clone.value = "";
    
    var destino = document.getElementById('destino');

    destino.appendChild (clone);
    
    // após adicionar ao DOM, aplica o maskMoney
    aplicarMaskMoney($(clone));
    
    // restante do código aqui
}
#destino {
  display: inline-block;
  width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>

<input type="text" id="valor"  name="valor[]" />
<br />
<button id="clonar">Clonar</button>
<br />

<div id="destino"></div>

EDIT: to clone the entire element containing several elements within, the following changes can help:

  • remove the ids of the elements that can be cloned
  • add name or class to help make a selector to access these elements:

var origem = $("#origem");
aplicarMaskMoney(origem);

// function para aplicar o maskMoney
function aplicarMaskMoney(obj) {
    $(obj).find(".valor").maskMoney({showSymbol:true, symbol:"R$", decimal:".", thousands:""});
}

function duplicarCampos(){
    var clone = document.getElementById('origem').cloneNode(true);
    var destino = document.getElementById('destino');
    destino.appendChild (clone);

    // pega os elementos "valor" e limpa
    $(clone).find(".valor").val("");
    // aplica a máscara
    aplicarMaskMoney(clone);
}

function removerCampos(id){
    var node1 = document.getElementById('destino');
    node1.removeChild(node1.childNodes[0]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>

<div class="form-body" id="origem">
   <div class="row" >
      <select name="empresa[]" class="select empresa" style="width: 30%">
         <option value='00'>Selecione Empresa</option>
         <?php
            $result = mysqli_query(...);
            while($row = mysqli_fetch_array($result) ){
            echo "<option value='".$row['id']."'>".$row['NomeEmpresa']."</option>";
            }
            ?>
      </select>
      <select name="filial[]" class="select filial" style="width: 30%">
         <option value="0">Escolha uma filial</option>
      </select>
      <input type="text" name="valor[]" class="valor" style="text-align:center; width: 20%"/>  
      <img  src="img/add.png" width="20px" height="20px" style="cursor: pointer;" onclick="duplicarCampos();">
      <img  src="img/del.png" width="20px" height="20px" style="cursor: pointer;" onclick="removerCampos(this);"> 
   </div>
</div>
<div id="destino">
</div>

Browser other questions tagged

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