How to use . click on jQuery after return from ajax

Asked

Viewed 90 times

0

I have an ajax function that returns content with a button. I would like to call another function triggered by the button that the ajax returned, as in the example below:

<button id="procurar" type="button">Procurar</button>
<div id="resultado"></div>
<script>
$("#procurar").click(function(){
        buscadados();
});

$("#procurar").click(function(){
        meuretorno("Botão retorno funcionou!");
});

function buscadados(){
        $.ajax({
            type: "POST",
            url: "/dados.php",
            data:  {
                cep:"valor"
                },
            dataType: "html",
            error: function(){
                alert('Erro');
            },
            success: function(html){
                $("#resultado").html(html);
            }
        });
    }
</script>

And in the dados.php, something simple:

<button id="meuretorno" type="button">Botão retorno</button>

It returns the right value, but when clicking the button #meuretorno, nothing happens, I think because it was inserted by ajax.

I can identify the click of this new button?

1 answer

1


When we dynamically add elements to the DOM, using the on() from Jquery to map the event.

More here in the documentation: https://api.jquery.com/on/

Look at this example:

$('body').on('click', '.bt', function() { 
  alert("oi"); 
});

$('#testar').click(function() {
   var elemento = $("<button class='bt'>Clique aqui, fui adicionado dinamicamente</button>");
   $("#resultado").append(elemento);

});
.resultado {
  display: inline-block;
  border: solid 1px blue;
  margin-top: 50px;
  width: 100px
}
<p>
   <button id="testar">Clique aqui para gerar o novo elemento</button>
</p>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="resultado"></div>

  • In this on() or click() code example, it makes no difference if you add the dynamic content after the button action declaration, both will not work. The correct one would be to orient that selector of the . on() has to be an ascending element that has not been dynamically added and then in the second parameter of . on() inform which selector (dynamically added) the click should look for. In this answer question explains better.

  • I edited the code to demonstrate when you add elements dynamically to take any questions

  • Now yes with the dial on Document makes a difference.

Browser other questions tagged

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