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?
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.
– Laércio Lopes
I edited the code to demonstrate when you add elements dynamically to take any questions
– Ricardo Pontual
Now yes with the dial on Document makes a difference.
– Laércio Lopes