0

First of all I have checked many similar questions on here and other resources, but I'm still unable to find the solution I require. I have a button that links to a specific page within my application and I also have a confirm() box that asks if the user wants to continue, if they click ok then the next page should be loaded, if they click cancel the new page should not load, as if the button was never clicked at all. Below is my HTML for the button:

<a href="http://localhost:9000/index">
    <button onclick="myFunction()" type="button" class="btn btn-outline-primary btn-lrg" style="font-size:20px;">CANCEL</button>
</a>

And now my JS for the confirm box:

<script>
  function myFunction() {
    if (confirm("Are you sure you wish to cancel this configuration?")) {
      return true;
    } else {
      return false;
    }
  }
</script>
Nathan Janman
  • 25
  • 1
  • 7

1 Answers1

0

The issue right now is that your button is triggering the function, however your link is the one that's redirecting.

That in mind, wrapping a <button> with an <a> is invalid:

Content model: Transparent, but there must be no interactive content descendant.

The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).


Some alternatives:

Use a <form> instead of an <a>

<form action="https://stackoverflow.com">
    <button type="submit" onclick="return confirm('Are you sure?')" class="btn btn-outline-primary btn-lrg" style="font-size:20px;">CANCEL</button>
</a>

Remove the <a> entirely

function btnCancel() {
  if (!confirm("Are you sure?")) return false;
  location.href = "https://stackoverflow.com";
}
<button type="button" onclick="btnCancel()" class="btn btn-outline-primary btn-lrg" style="font-size:20px;">CANCEL</button>

Remove the <button> entirely

<a href="https://stackoverflow.com" onclick="return confirm('Are you sure?')">Cancel</a>
Community
  • 1
  • 1
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
  • Thank you so much, I used the '
    ' and it's worked perfectly for me. I have upvoted your answer but will not display publicly
    – Nathan Janman Jan 09 '19 at 14:30