0

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()"
5
  • 4
    "I am not sure if this is the correct syntax or not."? Have you tried it? Did it work? Are you asking if there is a better way? Commented Sep 19, 2014 at 20:33
  • Yes, your syntax is correct, although not a best practice. Instead of putting code into your inline onclick handler, write a separate save function and add it via addEventListener. Commented Sep 19, 2014 at 20:33
  • FYI, addEventListener is not supported by some/all versions of Internet Explorer. Commented Sep 19, 2014 at 20:38
  • @Karl-AndréGagnon - I have tried it and no it did not work. I get an error telling me that AveryValidateAddress is undefined, though that is the exact name of the function it references. Commented Sep 19, 2014 at 20:50
  • @KevinSchultz Your function must be in a closure. Check if you function is not inside a DOM ready or any other function. Commented Sep 19, 2014 at 21:01

3 Answers 3

4

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()
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try:

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

Comments

-1

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>

2 Comments

Where does it say he is using jQuery?
@SableFoste He had the jQuery tag on the question before it was edited

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.