0

I'm trying to stop execution of Javascript event handler when some condition is satisfied, and my code looks like this:

 $(".save").click(function (event) {
            $(".loader").fadeIn(300);

            var statusValue = $("#status").val();
            console.log(statusValue);

            if (statusValue == null || statusValue == '') {
                $("#status").css({
                    "border-color": "red",
                    "border-width": "1px",
                    "border-style": "solid"
                });
                event.preventDefault();
                console.log("NOT EXECUTED");
            }

            console.log("EXECUTED");
// .. some more code
}

When I check console I'm getting results like this:

null
null
NOT EXECUTED
EXECUTED

So I'm wondering how come? If == null condition is satisfied shouldn't event.preventDefault() stop this .click event from execution till end?

I'm trying to achieve, if nothing is selected in then prevent execution, my select looks like this:

<select class="form-control" id="status">
        <option value="Done">Done</option>
        <option value="Complited">Completed</option>
        <option value="Cancel">Cancel</option>
</select>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
billy_56
  • 649
  • 3
  • 11
  • 27

4 Answers4

0

The event is already happening. You can use this:

 $('form').attr('onsubmit', 'return false;');
0

No, event.preventDefault() doesn't do what you're thinking, in this case if you want to stop the function execution you can just but a empty return; at the end of the if block. Another solution is put an else block.

event.preventDefault() prevents the default action to happen, for an example, if you put it on a <a>link</a> it won't redirects to the href, because the default of a click on a a is to redirect the page to the path on href prop. Example.

Gabriel Carneiro
  • 643
  • 5
  • 16
0

event.preventDefault() does not work in your case, use return; instead

$(".save").click(function (event) {

    if (true) {
      console.log("EXECUTED");
      return;
      console.log("NOT EXECUTED");
    }

    console.log("NOT EXECUTED");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
  <button class="save">Save</button>
</div>
0

To stop it use this:

throw new Error("Something went badly wrong!");

source: https://stackoverflow.com/a/9298915/4110122

Mohamad Hamouday
  • 2,070
  • 23
  • 20