First I tried:
document.getElementById(trade_selection[i].slug).onclick = send_trade_request(auction_a, slug_for_trading, username);
but it triggered the function before any click event took place, so I found that I need to call anonymous function in order to make it work, so I tried that:
var slug_for_trading = 'slug for trading';
var trade_selection = [{
name: 'foo',
slug: 'niceslug',
selling__username: 'foo',
price: 123
}, {
name: 'foo1',
slug: 'veryveryniceslug',
selling__username: 'foo1',
price: 123
}];
var el = document.getElementById('test');
el.innerHTML = "TRADE <br>";
for (var i = 0; i < trade_selection.length; i++) {
var username = trade_selection[i].user_selling__username;
var auction_a = "<a href='http://example.com/foo/" + trade_selection[i].slug + "'>" + trade_selection[i].name + "</a>";
var trade_request_button = "<button id='" + trade_selection[i].slug + "'>Send Trade Request</button>";
el.innerHTML = el.innerHTML + "- Auction name: " + auction_a + " | Price: " + trade_selection[i].price + trade_request_button + "<br>";
console.log(document.getElementById(trade_selection[i].slug));
document.getElementById(trade_selection[i].slug).onclick=function(){
send_trade_request(auction_a, slug_for_trading, username);
}
}
function send_trade_request(auction_a, auction_b, to) {
alert(auction_a + " " + auction_b + " " + to);
}
<div id='test'>
</div>
and it works, except that the first button doesn't call the function at all. I can't seem to figure out why that's. Looking for some direction.
console.log(document.getElementById(trade_selection[i].slug)before adding an event handler to see if you getundefined. If that is the case I am right.