Jason
Jason

Reputation: 21

JS button prompt with Yes/No options

Creating a "Remove Token" button that will alert the user with a confirmation "Yes" or "No". Won't work with my current code:

<button onclick="alertFunction">Remove Token</button>
  <script>
  function alertFunction() {
  if (confirm('Remove token?')) {
    return;
  } else {
  return false;
  }
  }
  </script>

What am I doing wrong? Thanks.

Upvotes: 1

Views: 1344

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

The main problem comes from the missing parentheses () in the following line :

<button onclick="alertFunction()">Remove Token</button>
______________________________^^

I suggest to avoid the inline-event onclick and use addEventListener() instead :

document.getElementById('my-button').addEventListener('click', function() {
  if (confirm('Remove token?')) {
    console.log('OK');
  } else {
    console.log('Cancel');
  }
})
<button id="my-button">Remove Token</button>

Upvotes: 2

lordoftheFlies
lordoftheFlies

Reputation: 56

<button onclick="alertFunction">Remove Token</button>

should be

<button onclick="alertFunction()">Remove Token</button>

but using Zakaria's approach is likely the more correct one for this type of functionality. Generally speaking its a good habit to keep any functions outside of your markup.

Upvotes: 0

Matthew P
Matthew P

Reputation: 735

You are just missing the () when you call the function i.e. onclick="alertFunction()"

Currently the onclick event is just trying to use a variable and not run your function.

Full code:

<button onclick="alertFunction()">Remove Token</button>
<script>
  function alertFunction() {
    if (confirm('Remove token?')) {
      return;
    } else {
      return false;
    }
  }
</script>

Upvotes: 0

Related Questions