Pass Dynamic Object in Onclick - Javascript/Jquery

Pass dynamic object in onclick - JavaScript/jQuery

Try attaching the listener properly using event listeners in Javascript rather than inline HTML attributes (which is as bad as eval). Also, when you use bind, the first argument is the this value provided to the function; the second argument to .bind corresponds to the first argument in the other function.

function handleProductsClick(product) {  console.log(product && JSON.stringify(product));}
function buildProducts(products) { products.forEach(product => { const li = $('<li>' + product.value + '</li>'); li.on('click', handleProductsClick.bind(null, product)); $("#products").append(li) });}
function getProductsFromApi() { var products = [{ key: 1, value: "Apple" }, { key: 2, value: "Android" } ]; buildProducts(products);}
getProductsFromApi();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="products"></ul>

How to pass variables to a dynamically created javascript onclick function?

Fixed it. The problem was that $i wasn't declared and even if it was, it was updated to the last $i value, not the iteration. Also the problem was that $results wasn't declared globally.

To solve this I did the following:

var $globalResults;

...
{
button.id = $i;

button.onclick = function(event){
var $j = event.currentTarget.id;
UpdateModal($globalResult[$j]["id"]);
}
}

How to pass an object in a dynamically created function call

Instead of trying to inline the event handling use jQuery .on()

var img = $("<img class='thumbnail' id='img_"+id+"' src='../images/products/thumbs/"+file_name+"' />")
.on('click', function(){
openDialogue(obj);
return false;
}) ;
$("#imageBox_"+id).append(img);

Pass a JSON array into dynamically created onclick method of button jQuery

Since it seems that you're using jQuery, I would suggest that you add the listeners manually, but to do that you would need to create the elements and store them in variables prior.

Obs.: this code can be made much shorter and simpler, but for sake of readability I've done this way.

function populateData(data) {
$(".studentPanel").show();
for (var i = 0; i < data.length; i++) {

$(".totalFee" + i).val(data[i].total.amount);

for (var j = 0; j < data[i].submissions.length; j++) {

var ts = new Date(data[i].submissions[j].created_at);
var dateString = ts.getDate() + "-" + ts.getMonth() + "-" + ts.getYear();
console.log(data[i].submissions[j].amount);

var
tr = $("<tr>"),
td1 = $("<td>"),
td2 = $("<td>"),
td3 = $("<td>"),
td4 = $("<td>"),
btnUpdate = $("<button class='btn btn-primary Update'>"),
btnDelete = $("<button class='btn btn-danger Delete'>");

$(".feeTable" + i).append(tr);
tr.append(td1).append(td2).append(td3).append(td4);

td1.append(data[i].submissions[j].amount);
td2.append(dateString);

td3.append(btnUpdate);
td4.append(btnDelete);

btnUpdate.append("Update");
btnDelete.append("Delete");

btnUpdate.click((event) => {
//put whatever your updateFees function does in here
console.log(event);
console.log(data[i].submissions[j].id); //your data is acessible
});

btnDelete.click((event) => {
//put whatever your deleteFees function does in here
console.log(event);
console.log(data[i].submissions[j].id); //your data is acessible
});
}
}
}

I also suggest you to take a good look on jQuery and javascript good pratices.

Jquery: onclick event added to dynamically created <li> while parsing JSON is giving error when clicked

Try using this

$('#bullets').append('<li id="demo" onclick="loadCards(\'' + element.id + '\')">' + element.name + '</li>');

As exemplified by this fiddle:

passing dynamic value to onclick function - CodeIgniter

If your pr_id is auto-increment column then just order by your result using pr_id. Because ordering by integer column is fast.
And in your case there is a possibility of new record is inserted after you fetched the latest pr_id. So there is no fool-proof solution
to handle your case.
So, When you call finalize(), again check your current pr_id value is latest one. Based on that you could handle your logic.

To create tr & td dynamically and append to table. Onclick pass the json selected object

You can set value of row as json object i.e :{'datas': row} inside click event handler and then access this using event object .i.e : e.data.datas .

Demo Code :

function populateResult(data, resultElementId) {
$.each(data, function(i, row) {
$trs = $(`<tr><td> ${row.name} </td></tr>`).appendTo(resultElementId);
//on click pass that row as well
$trs.on('click', {
'datas': row
}, myfunction);
})

}
function myfunction(e) {
//use event object to access data
console.log('Data : ' + JSON.stringify(e.data.datas));
}



populateResult([{
"name": "s1",
}, {
"name": "s2"
}], "#myTableBody")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<table>
<tbody id="myTableBody"></tbody>
</table>


Related Topics



Leave a reply



Submit