how to get the text inside the dynamically rendered items on the click of the button?

Viewed 57

I am displaying the content after fetching it via ajax using jquery so the content is dynamic,

var i, j;
var product_names = [];
var product_image = [];
var product_rate = [];
var product_amount = [];
var product_category = [];
$.ajax({
    url: BASE_URL + '/getOrgServices?orgId=' + orgId,
    type: 'GET',
    success: function(result) {
        //console.log(result);
        for (i in result) {
            product_names[i] = result[i].name;
            product_image[i] = result[i].imgurl;
            product_rate[i] = result[i].rate;
            product_amount[i] = result[i].amount;
            product_category[i] = result[i].categories;
        }

for(i in product_category){
                var html = '<div class="prod-content"><ul id="products">';
                html += '<li class="row product-listing">';
                html += '<div class="product-img-container"><img class="product-img" src="' + product_image[i] + '"></div>';
                html += '<div class="container product-listing-details"><h6 id="product-title">' + product_names[i] + '</h6><div id="product-description">' + product_amount[i] + '</div><br><div id="product-cost">' + product_rate[i] + '</div></div>';
                html += '<div id="product-add">';
                html += '<button class="add-button" type="button" role="button">ADD</button>';
                html += '<span class="quantity"><input class="item-quantity" type="number" value="0" min="0" max="50" step="1"></span>';
                html += '</div></li> </ul></div>'
            
                //adding elements to all category
                var id_str = '#' + new_id[0];
                $(id_str).append(html);
 }

}

Now in the below function i want to access the name of one h6 product_name at a time so is there any method to do so like if I could select

$(".add-button").click(function() {
        //here i want to add items to cart on button click (means the button clicked its corresponding item should be added to cart )
   });

is the cart part of the html code

  <div class="order">
      <ul id="products">
       <li>
          //here i want to append the added item
       </li>
     </ul>
   </div>
1 Answers

To get all h6 you can do similar thing as below, without jQuery.

$(".add-button").click(function() {
  console.log("click");
  document.querySelectorAll("div.prod-content h6").forEach((function(elem) {
    console.log(elem.innerText);
    if (parseInt(elem.innerText) > 0) {
      console.log(elem);
    }
  }));
});

Related