Imad
Imad

Reputation: 7490

Cannot stop JQuery event

Here is the simplified scenario

$(function() {
  $('#btn').on('click', function() {
    alert('JQuery')
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id='btn' value="Button" onclick="alert('onclick');return false;" />

two alerts are called even though I have returned false. How can I prevent script written inside ready event?

Upvotes: 2

Views: 55

Answers (2)

Satpal
Satpal

Reputation: 133453

You need to use event.stopImmediatePropagation() to prevents other listeners of the same event from being called.

$(function() {
  $('#btn').on('click', function() {
    alert('JQuery')
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id='btn' value="Button" onclick="alert('onclick');event.stopImmediatePropagation();" />

Upvotes: 1

Sergey Sklyar
Sergey Sklyar

Reputation: 1970

You should stop the alert('click') before you call the alert function. Usually it can be done with event.preventDefault() used within a function

$(function() {
  $('#btn').on('click', function() {
    alert('JQuery')
  })
  function alert_first(event){
      event.stopPropagation();
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id='btn' value="Button" onclick="alert_first();alert('click);"/>

Upvotes: 0

Related Questions