Home > database >  How to get data from dynamically generated element using jQuery
How to get data from dynamically generated element using jQuery

Time:09-16

I want to do something with data from dynamically generated element, like printing the data from the clicked element, how can I do that?

here's my jquery code:

let setHistory = () => {
   $('#transaction-history').empty();
    transactionHistory.forEach((o) => {
        var htmlBlock = "";
        htmlBlock  = `<div class="btn btn-outline transaction-history-item d-flex flex-column justify-content-center mr-4">`
              `<img class="transaction-history-item-image card pl-2 pr-2 pt-1 pb-1 mx-auto" src="../assets/placeholder-image.png" alt="" >`
              `<div class="transaction-history-number mt-1 mx-auto">${o.meterNumber}</div>`
              `<div class="transaction-history-value mx-auto" data-value=${o.value}>Rp${o.value.toLocaleString().replaceAll(',','.')}</div>`
              `</div>`;
        $('#transaction-history').append(htmlBlock);
    });
}

and the transactionHistory data looks like this:

 let transactionHistory = [
    {
        meterNumber: "1234152322",
        value: 250000
    },
    {
        meterNumber: "1115648463",
        value: 50000
    }
]

and here's the illustration of the dynamically generated element: enter image description here

Basically, I want to get the meterNumber and value from the card I clicked, how can I implement that?

CodePudding user response:

You can get desired data by using Codepen example

using next() function :

$(document).on('click', '.transaction-history-item-image', function() {

    var tranNumber = $(this).next().html();
    var tranValue = $(this).next().next().html();

});

or by using parent() and find() :

$(document).on('click', '.transaction-history-item-image', function() {

    var tranNumber = $(this).parent().find('.transaction-history-number').html();
    var tranValue = $(this).parent().find('.transaction-history-value').html();

});
  • Related