0

I have the following click event that is being fired multiple times although I click only once

$(document).on('click', '#addToList', function (event) {
     event.preventDefault();
     ...
 });

I read here you should use the off method e.g.

 $(element).off().on('click', function() {
     // function body
 });

however my jquery event is on the document since I load the control dynamically.

How do I add the off code to my event?

dfmetro
  • 4,142
  • 6
  • 36
  • 62
  • You must be associating multiple event handlers. Problem seems to be somewhere else. Can you show us How you are generating the element and attaching event handler? – Satpal Jul 12 '17 at 08:34
  • @devc2 check my answer.. it will definitely help you.. even i had this same issue.. – SwapNeil Jul 12 '17 at 08:44

2 Answers2

3

Simply reverse it first:

$(document)
    .off('click', '#addToList')
    .on('click', '#addToList', function() { ... })
StudioTime
  • 20,816
  • 34
  • 110
  • 202
-1

You could try using

$(document).off('click', '#addToList').on('click', '#addToList', function (event) {
    event.preventDefault();
    ...
});

Firstly removing the click binding event, through the off method, and chaining it onto an on click event, rebinding the function.

Joel
  • 100
  • 6
Sheikh Azad
  • 323
  • 2
  • 11