Kevin Schultz
Kevin Schultz

Reputation: 884

If statement then click event in JavaScript

I am trying to only allow a click event to fire if a function return is true. I am not sure if this is the correct syntax or not. Any help would be awesome.

onclick="if(AveryValidateAddress())Shipping.save()"

Upvotes: 0

Views: 127

Answers (3)

Brett
Brett

Reputation: 589

The way you have it written, you could accomplish this by taking advantage of the && operator's lazy evaluation. If the first part of your and statement evaluates to false, it won't attempt to evaluate the second part.

onclick="AveryValidateAddress() && Shipping.save()"

However, since you're using jQuery, a better approach would be to take advantage of jQuery's event binding:

<a href="#" id="saveButton">Click to save</a>

<script>
$(document).ready(function(){
    $('#saveButton').click(function(){
       if( AveryValidateAddress() ){
          Shipping.save();
       }
    });
});
</script>

Upvotes: -1

Apul Gupta
Apul Gupta

Reputation: 3034

Try:

onclick="AveryValidateAddress() && Shipping.save()"

Upvotes: 0

Cyril Duchon-Doris
Cyril Duchon-Doris

Reputation: 13949

Why would you not include the check Inside the function ?

HTML

onclick="myFunction()"

JS

myFunction = function(){
  if (!AveryValidateAddress()){
     //Dont do anything if it's false
     return
  }
  else{
      Shipping.save()
  }
}

Upvotes: 4

Related Questions