'how to add click only on button

I am using jquery to bind a click on a button. In this var testId i am getting the id of the button and var showmoreId is getting the id of a div but the problem is onclick binds with the li so when i click anywhere in li onclick is working but i want it to work on button click and i also want the id of the div on click but do not want li to work on click so what can i do to fix it.

async function userData(userdata) {
    let newValue = ""; 

userdata.forEach(max=> { 
let add =  `<div class="rb-container">
            <ul class="rb">
            <li>
            <div>
            <p>${max.name}</p>
    
            <div>
            <p>${max.email}</p>
            <button id="showMoreLess_${max.id}" data-order-id="${max.id}">View More</button>
            </div>
                
            <div id="showme_${max.id}" class="showBlock" style="display:none";>
    
            <div>
            <div>
            <p>Quantity:</p>
            <p>${max.volume}</p>
            </div>
            <div>
            <p>${max.group_email}</p>
            <p>Group_Email</p>
            </div>
            </div>
        </div>
            </div>
            </li>
</ul>
</div>`


 newValue += add ;
 let container = document.querySelector('.user-details');
    container.innerHTML = newValue;

}

$(document).ready(function() {
        $('.rb-container li').unbind('click');

        $('.rb-container li').on('click', function () { 
            var testId = $(this).find('button').attr('id');          
            var showmoreId = ($(this).find('div > div').next().attr('id'));
            
            viewFullDetails(testId, showmoreId);
        });


Solution 1:[1]

The .on() function supports an optional selector to handle events on certain child elements.

    $('.rb-container li').on('click', 'button', function() {
        var testId = $(this).attr('id');
        var showmoreId = $(this).closest('li').find('div > div').next().attr('id');
        
        viewFullDetails(testId, showmoreId);
    });

Note that I just added the selector 'button' but of course you can use any selector, e.g. #id. I then found the closest li to go from there to get the showmoreId.

Please also consider to use .off() instead of .unbind() as the latter has been deprecated.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1