-1

I am adding a row to the html table on click event of a button. Inside that row, I have 1 cell which contains li element. I have assigned click event for that li element. When I click on li the event gets fired many times, i dont know why...kindly help.

<input id="btnAddRow" type="button" value="Add Row" />
<div id="mainSection">
    <table id="tblList" border="1" cellpadding="1" cellspacing="1">

    </table>
</div>
$(document).ready(function ()
{
    $('#btnAddRow').click(function ()
    {
        $('body').on('click', 'li', function () {
            alert($(this).text());
        })
        var markUp = '<tr><td>1</td><td>2</td><td>3</td><td><li>Hello</li></td></tr>';
        $('table').append(markUp);
        $('table').on('click', 'li', function () {
            alert($(this).text());
        })
    })

});
Imran
  • 13
  • 5
  • 1
    Does this answer your question? [jQuery click events firing multiple times](https://stackoverflow.com/questions/14969960/jquery-click-events-firing-multiple-times) – snwflk Feb 17 '20 at 19:06
  • https://html.spec.whatwg.org/multipage/grouping-content.html#the-li-element Also keep in mind that you are creating non-web standard compliant html, as `li` are expected to be children of an `ol`, `ul`, or `menu`. – Taplar Feb 17 '20 at 19:10
  • @KevinB — You're acting way too fast. The question that snwflk linked isn't actually the same, despite the title. – coreyward Feb 18 '20 at 00:22

1 Answers1

-1

You're binding the click handler multiple times.

// on each click…
$('#btnAddRow').click(function() {
  // bind a click event on body
  $('body').on('click', 'li', function () {
    alert($(this).text());
  })
  // ...
  // bind a click event on every table
  $('table').on('click', 'li', function () {
    alert($(this).text());
  })
})

As a result, every time your #btnAddRow is clicked you add two additional event handlers, one to body and another to all table elements.

coreyward
  • 77,547
  • 20
  • 137
  • 166