I have the following situation, I am uploading a code from Php to html with jquery . What is happening to me is that from the code that I am printing from Php when it shows it to me in the html it does not recognize the jquery selector ( a.deleteComec ) that I am printing from Php . Then I leave the code to see if you can help me. Thanks.
php code
foreach ($datos as $val){
if($usuario == $val['idusuario']){
echo '<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title" >'.$val['nombre']." ".$val['fechahora'].'<div class="text-right"><a class="deleteComec" id="'.$val['id'].'" href="#" title="Borrar">Borrar</a></div></h3>
</div>
<div class="panel-body">'.
$val['comentario']
.'</div>
</div>';
}else{
echo '<div class="panel panel-warning ">
<div class="panel-heading">
<h3 class="panel-title" >'.$val['nombre']." ".$val['fechahora'].'<div class="text-right"><a class="deleteComec" id="'.$val['id'].'" href="#" title="Borrar">Borrar</a></div></h3>
</div>
<div class="panel-body">'.
$val['comentario']
.'<div>
</div>';
}
}
Loading the content to the html with jquery
var cargarmensaje = function(){
idcoment = $("input#id").val();
$.post("index.php?c=pendientes&f=getcomentario",{id: idcoment},function(data){
$("#listcomentario").html( data );
});
}
Where the selector is executed (a.deleteComec)
$('a.deleteComec').on("click",function () {
id = $(this).attr('id');
bootbox.confirm("Está eguro que desea borrar. Recuerde que al borrar, se eleminaran todos los datos asociados en Cascada", function (result) {
if (result) {
$("div#idloader").addClass("loader");
$.post('index.php?c=' + a_id[1] + '&f=delComec', {id:id}, function (data) {
cargarmensaje();
$(".loader").fadeOut("slow");
});
}
});
});
How the code is displayed in the browser
<a class="deleteComec" id="144" href="#" title="Borrar">Borrar</a>
I'll tell you, this happens because of the order in which the events are associated with the dynamic elements. What you could do is refresh the listener , first removing the handlers and then the ReAssociates
Then you can add this function when you think it's necessary. By default in the
$(document).ready
Or when you think that more elements are added to that class, for example an ajax
The problem is that it
.on()
only works on existing elements and not directly on dynamic elements. Try changing your selector to this: