Dynamic button creation

Asked

Viewed 42 times

2

Hello. I’m hitting myself to create a button for every result that the $.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");});

Someone could give me a boost?

  • Instead of using $("#lista").html($html);, use the "append" method, thus $("#lista").append($html);, because the way you’re doing, every time he’s replacing the last html added.

  • Vlw. I will make the change.

  • If it works, let me know to mark it as a response. See more information here if you need: W3schools - jQuery DOM Add.

  • Your code works: https://jsfiddle.net/6osc71sv/ What exactly is the problem you are experiencing?

  • I cannot create an id for the button it generates with each result. I can’t tell the id of the button, id="btn_orc'+Orc.numero+'", but I can’t use it.

  • It is generating correctly, can edit your question by placing the code snippet that is trying to use it?

  • put there ;).

Show 2 more comments

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 the this inside the callback is the button clicked. The first solution works if the elements are already on the page, what you do in the previous line with $('#lista').html($html);, the second solution works provided that #lista exists.

  • It worked here, Sergio. Thank you very much.

  • The second argument of the second solution delegates the event click on buttons inside #lista @Sergio? It would be equivalent to $('#lista > button')? Or has a different purpose if the gift has been manipulated via code..

  • 1

    @Lucascosta yes and no, in this second case it allows clicks on buttons that are added after that code has run. Where $('#lista > button') is for elements only button direct descendants of #lista that exist on the page when that code runs.

  • @Sergio owe you a beer, man. Vlw ^^

  • @Marcelp Aha, I don’t drink beer :) but I’m glad I helped!

Browser other questions tagged

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