2

My code shows this error in the console:

Uncaught TypeError: confirm is not a function

I can resolve it by renaming the input to something other then "confirm".
Why would naming an input conflict with JavaScript's confirm function?

<form action="" method="POST">
  <input type="text" name="confirm">
  <input type="submit" onclick="return confirm('Text')">
</form>
showdev
  • 28,454
  • 37
  • 55
  • 73
  • "Why would naming an input conflict with javascripts confirm function?" - because someone at Netscape or Microsoft thought it would be a good idea back in 1997. – Dai Apr 13 '21 at 21:14
  • 1
    Try `window.confirm` instead. – Dai Apr 13 '21 at 21:15

1 Answers1

3

In JavaScript, the names of input elements become properties of the associated form object. In your case, the input named "confirm" becomes a property of its form, which shadows the confirm method inherited from the window object.

window.confirm => form.confirm
<input type="text" name="confirm"> => form.confirm

As mentioned by Dai in comments above, you can use window.confirm() to ensure that you access the confirm method of the window object.

<form action="" method="POST">
  <input type="text" name="confirm">
  <input type="submit" onclick="return window.confirm('Text')">
</form>

Or, as referenced in your question, use a different input name:

<form action="" method="POST">
  <input type="text" name="confirmation">
  <input type="submit" onclick="return confirm('Text')">
</form>

For more reference, also see:

HTMLFormElement

Warning: Avoid giving form elements a name that corresponds to a built-in property of the form, since you would then override the predefined property or method with this reference to the corresponding input.

input name called submit
confirm is not a function
confirm not working

showdev
  • 28,454
  • 37
  • 55
  • 73