Jump to content

Return False in OnClick


ShoeLace1291

Recommended Posts

I'm trying to make an onclick script that changes the action of a link and form if OK is clicked in the confirm prompt.  I'm getting a syntax error in firebug at the return false part.

 

Basically, if the user clicks OK, I want the script to change the action of the form to the href of the link they clicked and then submit the form.  I'm still somewhat new to JS, but here's my code.

 

 

<a href="http://localhost/restaurant/admincp/forums/categories/delete/1" onclick="confirm('Are you sure you want to delete the category \'General Discussions\'?  This action CANNOT be undone.') ? document.getElementById('actionform').action = this.href; document.getElementById('actionform').submit() : return false;"><img src='http://localhost/restaurant/template/images/delete.png' width='27' height='27' border='0' alt='Delete'></a>

 

Link to comment
Share on other sites

ternary operators can only have 1 expression for true and 1 expression for false.  Since you have 2 expressions for your true condition, you must wrap it in something like a function and call the function instead, or put an anonymous wrapper function around it.

 

But in general, you don't want to stuff everything inside the onclick like that.  You should put everything in a wrapper function to make it a lot cleaner:

 

<a href="http://localhost/restaurant/admincp/forums/categories/delete/1" onclick="confirmDelete(this);return false;"><img src='http://localhost/restaurant/template/images/delete.png' width='27' height='27' border='0' alt='Delete'></a>

<script type='text/javascript'>
function confirmDelete(that) {
  var c = confirm("Are you sure you want to delete the category 'General Discussions'?  This action CANNOT be undone.")
  if (c) {
    document.getElementById('actionform').action = that.href; 
    document.getElementById('actionform').submit();
  } else {
    return false;
  }
}
</script>

 

Even better would be to attach the wrapper function via an event listener to keep the javascript completely out of the anchor tag.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.