call onclick when the content is loaded from javascript

You’re having an issue here because you’re trying to set the click event for #copyCodeButton before it’s added to the DOM and exists.

Attach the event handler after you’ve added the button’s HTML to the DOM:

// Load Transaction List Modal
function loadModalCopyGiftCardCode(giftcard) {

  // Show Modal
  $('#modalPopup').modal('show');

  var modalBody = '<div class="mt-4">';

  modalBody += '<div class="text-center col-md-12">';
  modalBody += '<img class="mb-3" src="assets/images/cards/qrcode.png" alt="QR Code" title="Scan QR Code for more details" width="150">';
  modalBody += '<p>Scan QR Code for redeemption on Offline & Online Store  </p>';
  modalBody += '</div>';

  modalBody += '<div class="form-group col-md-12">';
  modalBody += '<input type="text" class="form-control" id="giftcard" placeholder="GiftCard Number" value="' + giftcard + '" readonly>';
  modalBody += '</div>';

  modalBody += '<div class="form-group col-md-12">';
  modalBody += '<button type="button" id="copyCodeBtn" class="btn btn-primary btn-block" data-target="giftcard">';
  modalBody += 'Copy Gift Card Code';
  modalBody += '</button>';
  modalBody += '</div>';

  modalBody += '</div>';

  // Modal Title
  var modalTitle = '<h4>Gift Card Code</h4>';

  // Show Html on Modal Body
  $("#modal-cus-title").html(modalTitle);

  // Show Html on Modal Body
  $(".modal-body").html(modalBody);

  $('#copyCodeBtn').on('click', function() {
    var $this = $(this);

    // Get target
    var target = $this.data('target');

    // Select Key
    $('#' + target)[0].select();

    // Copy Key
    document.execCommand("copy");
  });

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>


<a href="javascript:void(0);" class="btn btn-primary d-inline mr-2" onclick="loadModalCopyGiftCardCode(12345667789988);">Show Code</a>

<div class="modal fade" id="modalPopup" tabindex="-1" role="dialog" aria-labelledby="modalPopup" aria-hidden="true" data-backdrop="static">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content card payment">
      <div class="modal-header">
        <!-- Modal Title -->
        <div class="modal-title">
          <!-- Custom Title-->
          <div id="modal-cus-title"></div>
          <!-- End Custom Title-->
        </div>
        <!-- End Modal Title -->

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
      </div>
      <div class="modal-body">
      </div>

    </div>
  </div>
</div>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top