1

I'm getting info from mysql then showing it in website and every {info} has a button which is added with .innerHTML = "Code";

I don't know how to make that I could press on that button which is added

for (i = 0; i < sameItems; i++) {
    Listings += '<tr>\
        <td>\
            <center>\
            <div class="avatar" style="padding-right: 6px; display: block;">\
                <img src="images/avatar/ignas.gif" style="border: 3px solid #5ad354;" width="48" height="48">\
            </div>\
            </center>\
        </td>\
        <td>\
            <center><img src="images/money-dollar-icon.png">'+ res[(i*3)+4] +'</center>\
        </td>\
        <td>\
            <center><button type="button" class="btn btn-success buylisting" id="'+ res[(i*3)+5] +'">BUY!</button></center>\
        </td>\
    </tr>';

    document.getElementsByClassName("marketListing")[0].innerHTML = Listings;
}

I need to click on button with class buylisting - I'm doing it like this

$(".buylisting").click(function () {
    console.log('test');
});

It doesn't work in my opinion it is because I'm adding the html after it loaded or something like that.

Can you assist?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
IgnasR
  • 172
  • 3
  • 10
  • _"because I'am adding the html after it loaded or something like that"_ - Precisely; you can only attach event handlers to already existing elements. I recommend you look into [event delegation](https://learn.jquery.com/events/event-delegation/) and delegate event handlers. The duplicate questions will have your answer. – John Weisz Jan 18 '16 at 17:43

1 Answers1

2

looking at your code, it appears that you are using jquery

in that case, use on() method

$( document ).on( "click", ".buylisting", function () {
    console.log('test');
});

using on() method, you can bind events before the elements are event added into the dom

gurvinder372
  • 66,980
  • 10
  • 72
  • 94