How to know when a button has been clicked, which was generated dynamically in JS?

1

I'm working on a web application implementing HTML , JAVASCRIPT , JQUERY

From JAVASCRIPT , I am adding code HTML , to generate buttons, as needed, within for , but I only add as I am adding it with the following code:

x +="<button type=\"button\" class=\"btn boton-eliminar-tratamiento\" name=\"DIENTE-1-TRATAMIENTO-1"\" >ELIMINAR</button>";
document.getElementById("p-tratamientos").innerHTML = x;

Until then everything works well for me. The buttons do appear in the HTML. My problem is when I now want to see if the user pressed that button. Try it with the following code:

$(".boton-eliminar-tratamiento").click(function(){
    alert('Ha hecho click sobre el boton'); 
    return true; 
});

In theory you should do it, but I'm pretty sure you have to see the button generate it dynamically from JS with innerHTML and that's why it does not enter the click .

    
asked by Angel Perez 21.04.2017 в 00:42
source

2 answers

3

Try changing your code portion:

$(".boton-eliminar-tratamiento").click(function(){
    alert('Ha hecho click sobre el boton'); 
    return true; // TIP: esto no es necesario de todas formas
});

To this code, which would be a delegated event listener (link in English):

$(document).on('click', '.boton-eliminar-tratamiento', function(){
    alert('Ha hecho click sobre el boton'); 
});

When you dynamically create elements and add them to the DOM tree they are not listened to by jquery through the common $('selector') , so you must use the delegated event listener with $(document).on('event', 'selector', callback) as I show you in the previous example.

    
answered by 21.04.2017 / 00:49
source
0

your code works perfectly only that at the end you mistakenly add 2 quotes: "... -1-TRATAMIENTO-1"\" >ELIMINAR ..." here I leave your code with a small modification in the literal assigned to x :

x='<button type="button" class="btn boton-eliminar-tratamiento" name="DIENTE-1-TRATAMIENTO-1">ELIMINAR</button>';
document.getElementById("p-tratamientos").innerHTML = x;

$(".boton-eliminar-tratamiento").click(function(){
    alert('Ha hecho click sobre el boton'); 
    return true; 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="p-tratamientos"></div>
    
answered by 21.04.2017 в 03:05