Search code examples
javascriptjqueryeventspreventdefault

Stop one of click events on the same button


I've button, with two click events on it. What I'm trying to do is to prevent both or all events on that button dependent on a criteria.

I tried to use event.preventDefault(); and event.stopPropagation(); and return false; but nothing works as I need.

/* I need to stop $('button') event if the if condition
inside $('#btn') event passed */

$('#btn').click(function(e){
  var term = $('#term').val();

  if(term != '') {
    //e.preventDefault();
    //e.stopPropagation();
    return false;
    alert(2);
  } else {
    // continue
  }
});

$('button').click(function(e){
  alert(1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="term" type="text" placeholder="type here ..">
<button type="button" id="btn">Check</button>

JSfiddle example


Solution

  • I assume you want to stop both events. If so you should add clause to your $('button').click() handler. First, in the $('#btn').click() handler add property to check if event should stop:

    if(term != '') {
        //e.preventDefault();
        //e.stopPropagation();
        this.stop = 1;
    ...
    

    Then check it:

      if (this.getAttribute("id") !== "btn" || this.stop !==1) {
          alert(1);
      }
    

    Here JSFiddle