Dynamic button creation

2

Hello. I am tapping to create a button for each result that $.each generates.

 $.each (data, function(index, orc){
           $html += '<div>';
           $html += '<button type="button" class="list-group-item" id="btn_orc'+orc.numero+'">Número: ' +orc.numero+'</br>Data: '+orc.data+'</br>Validade: '+orc.validade+'</br>Total: R$'+orc.total+'</br>'+'</button>';
           $html += '</div>';
    });
    $('#lista').html($html);
   // aqui não sei como implementar
   $('#btn_orc').on('click', function(){
        window.alert("clicou");});

Could someone give me strength?

    
asked by anonymous 22.11.2016 / 15:02

1 answer

2

You can use a selector that detects all IDs that start with a given string like this:

$('[id^="btn_orc"]').on('click', function() {
   alert("clicou");
});

Or you can delegate the event like this:

$('#lista').on('click', 'button', function() {
   alert("clicou");
});

Both do what you want and this within the callback is the clicked button. The first solution works if the elements are already on the page, what you do on the previous line with $('#lista').html($html); , the second solution works since #lista exists.

    
22.11.2016 / 16:32