Javascript return confirm() when input name=confirm gives confirm is not a function

Viewed 246

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>

1 Answers

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

Related