Home > Software design >  How to make jQuery function execute only once, even if we declare it multiple times in a form?
How to make jQuery function execute only once, even if we declare it multiple times in a form?

Time:10-09

I have a jQuery function when you click a button with particular class in a document, it will execute something. Ex. below.

$(document).on('click', '.tambah', function(){
  alert('tombol tambah telah ditekan');
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-md btn-success tambah">  tambah</button>

Lets say they are in the same script called 'script.php'. When I called the script once, the function of clicking that class will be executed once, but when I called the script again, when I clicked the button it executed twice. How to prevent it from executing more than one?

CodePudding user response:

If you are calling a function that performs the binding, then it can stack up. In a case like this you would usually "unbind" first

$(document).unbind('click').on('click', '.tambah', function(){
  alert('tombol tambah telah ditekan');
});

CodePudding user response:

event.stopImmediatePropagation(); [docs] should do the trick

$(document).on('click','.tambah',function(event){
    alert('tombol tambah telah ditekan');
    event.stopImmediatePropagation();
});
$(document).on('click','.tambah',function(event){
    alert('tombol tambah telah ditekan');
    event.stopImmediatePropagation();
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-md btn-success tambah">  tambah</button>

  • Related