jQuery . on('change', Function() {} does not work on select cloned

Asked

Viewed 290 times

-1

EDIT: I have an application that uses information from one select to another select using the ajax change function as below:

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

Follows code where I use this function:

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

This code I’m using inside a function that duplicates all my div, the problem I’m having is that from duplication the change no longer works in select created dynamically.

In practice, I have a select called company that populates the select called branch. Then when I double the div the second select subsidiary is not populated with the information of the second select enterprise, but with that of the first select.

Follow a print to make it easier to illustrate.

print

Below is the entire code of the page, I really appreciate anyone who can help me:

<!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>Lancamento Financeiro</title>
<link rel="stylesheet" href="/sistema/css/geralincluir.css">
<style>
.card-form {
  width: 900px;

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

  justify-content: flex-start;
  padding: 5px;

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

}
    
.card-form .form-body {
  padding: 2px;
}
    


</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">
    
    

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

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

    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>





</head>

<body bgcolor="#F5F5F5">



<br />

<div class="card-form">
   <form action="123.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 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>
        
    
    <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 put the html in the code, it’s confusing just looking at the js. "dynamically it does not work anymore" what do you mean input no longer works? input has no "working". If you have any event associated, you need to re-associate the new element, if an element has a "change" event for example and clone it, the new element will not have the same event associating

  • Isn’t that the same problem as your other question? https://answall.com/questions/504040/maskmoney-nao-funciona-em-input-duplicado-via-javascript

1 answer

0

The question is a bit confusing, but if you are creating elements dynamically. signing events in the load will not work.

There are 2 ways to solve this:

1 - pass Event to Parent and brush to the selector for the element you are creating. $( "selectorpai" ).on( "change", "selector[es]child[s]", Function() { console.log( $( this ).text() ); });

2 - create the event dynamicament together with the cloned element.

From the screenshot it looks like you have 3 selects and you are using a selector with id. This will not work and will end up signing the event only for the first element. I suggest you use a data attribute or even a css class to avoid this problem.

Browser other questions tagged

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