2

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?

Satpal
  • 132,252
  • 13
  • 159
  • 168
Imad
  • 7,126
  • 12
  • 55
  • 112
  • You should think about your profile pic and name, "Community" is a special user please don't use it – Satpal Nov 13 '17 at 08:11
  • https://stackoverflow.com/a/1357151/5378743 "`return false` does not stop the event from bubbling up." – Roland Starke Nov 13 '17 at 08:13
  • [event.stopImmediatePropagation()](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation) – Satpal Nov 13 '17 at 08:14
  • Possible duplicate of [jQuery prevent other events after a click](https://stackoverflow.com/questions/3472953/jquery-prevent-other-events-after-a-click) – Maxim Nov 13 '17 at 08:14
  • Possible duplicate of [event.preventDefault() vs. return false](https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) – Jasper Seinhorst Nov 13 '17 at 08:27

2 Answers2

1

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();" />
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

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);"/>
Sergey Sklyar
  • 1,902
  • 1
  • 15
  • 27