skip to Main Content

I’m having a problem trying to make this additemtolist fuction to work, the id=clickitemtoadd is a list loaded dynamicly with avalible items. but because is Dynamic load is not working.

Here is the code for onclick call a function:

function additemtolist(pos_name,item_id,pos_value){
  alert('clicked')
}
<p id="clickitemtoadd" onclick="additemtolist('item name','item id','item sales value')">item name</p>

2

Answers


  1. Chosen as BEST ANSWER

    I found a work around solution for someone with this problem

    Script:

    <script>
    $('#mainbody').on('click', '#clicitemtoadd', function(event) {
    var $this = $(this);  // Cache the clicked element
    
    if (!$this.data('processed')) {  // Check if it hasn't been processed yet
    $this.data('processed', true);  // Mark it as processed
    var dataitemid = $this.attr('data-item-id');
    alert(dataitemid);
    }
    });
    </script>
    

    html:

    <p id="clicitemtoadd" data-item-id="9999">9999</p>
    

  2. use live instead of inline onclick.deprecated

    Use Delegated event handlers :

    $(document).ready(()=>{
        $('#createBtn').on('click',()=>{
        $('<button id="actionBtn">Clickme</a>').appendTo('#ctn');
      });
      $('#ctn').on('click','#actionBtn',()=>{
        console.log('click');
      })
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div id="ctn">
    
    </div>
    <button id="createBtn">
    CREATE
    </button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search