1

When I select "Keyboard layout" it generate buttons using js - but click event not works with dynamic generated buttons. I think, it is because when document ready, element ".prices-tier" not exist. It generates, only when i select layout.

enter image description here

Part of my code:

    require(['jquery'], function(){
    jQuery(document).ready(function(){
        const currencySymbol = jQuery('.price').text()[0];
        var standartPrice = Number(jQuery('.price-wrapper').attr('data-price-amount'));



        jQuery('.prices-tier').on('click','.btn', function () {
            var quantity = Number(jQuery(this).attr("data-qty"));
            var price = jQuery(this).attr("data-amount");
            jQuery('.qty-default').val(quantity);
            jQuery('#product-price-'+"<?php echo $_product->getId();?>"+' .price').html(currencySymbol+price);
            // jQuery('.product-info-main>div>.price-box>.price-container>.price-wrapper>.price').html(currencySymbol+price);
            jQuery('.qty-default').trigger('input');
        }
        );

Generated html elements:

<div class="prices-tier items w-75 btn-group">

        <button type="button" class="btn btn-light border border-bottom-0 border-top-0 bg-primary" data-qty="25" data-amount="27.21" onclick="">

        4%</button>

        <button type="button" class="btn btn-light border border-bottom-0 border-top-0 bg-primary" data-qty="50" data-amount="26.5" onclick="">

        6%</button>
</div>
Ashen One
  • 371
  • 1
  • 12

1 Answers1

2

You need to use event delegation and attach your listener to a parent (that exists in the DOM already) or document. That way events can bubble up from new elements and be caught by the listener.

jQuery(document).on('click', '.prices-tier .btn', function () {

Note, this isn't just a jQuery trick, this is how JS events work. For example, it's also useful in instances where you have, for example, a list of items (1000) but you don't want to add an event listener to each one. You attach one event listener to the parent container (a <ul> perhaps), and that can catch all the events that bubble up from its children and process them.

Andy
  • 61,948
  • 13
  • 68
  • 95