Select change jQuery

Asked

Viewed 15,321 times

2

I have the following script:

$("#tp_pagamento").change(function(){
    var tp_pagamento = $(this).val();
    $.ajax({
        url: BASE_URL + "ajax/lista_integrador",
        type: "POST",
        data: {tp_pagamento:tp_pagamento},
        success: function(data){
            $('.tp_integradora').html("<select id=\"tp_integradora\" name=\"tp_integradora\" class=\"form-control\"><option value='0'>Carregando...</option></select>");
            setTimeout(function(){
                $('.tp_integradora').html(data);                    
            },1000);                        
        }
    });
});

$("#tp_integradora").change(function(){
    var tp_integradora = $(this).val();
    alert(tp_integradora);
    if(tp_integradora==1){
        $("#logo_integradora").html("<img src="+ BASE_URL + "/assets/images/integradora-cielo.jpg>");
    }
});

My idea is that: When selecting tp_payment, search the available ones and list in another select, and this does, however, I need that when selecting the next select, it has no action... How I can fetch the select data that was displayed on the screen?

1 answer

4


This is happening because you are clicking on an element that is being created dynamically, someone with a better knowledge of DOM can better explain the reason for this, but I have already gotten this problem. I recommend you take a look at jquery’s on() method. To solve this element, just take a parent element that is in html and was not created dynamically using on this way: $(elementoMae).on('evento','#elementoCriadoDinamicamente',function(){})

in your case try: $('#logo_integradora').on('click','#tp_integradora',function(){ codigo aqui });

Example:

$("#primeiroSelect").change(function(){
  let valor = $(this).val();  
  $("#mae").append(criaSelect)
})

$("#mae").on("change","#segundoSelect",function(){
  let valor = $(this).val();
 console.log("Valor Escolhido foi: "+valor);
})

function criaSelect(){
 let html = '<select id="segundoSelect" class="form-control"> <option value="4"> 4 </option> <option value="5"> 5 </option> <option value="6"> 6 </option> </select>'; 
 
 return html;
}
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css");
#segundoSelect{
  margin-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>
<div id="mae" class="container">
  <select id="primeiroSelect" class="form-control">
    <option value="1">
    1
    </option>
     <option value="2">
      2
    </option>
     <option value="3">
      3
    </option>
  </select>
</div>

Browser other questions tagged

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