6

Can someone explain me why a function called "action" creates a type error in the following code as soon as the button is surrounded by the form tags. I assume this leads to a strange conflict with the form's action attribute, but i wonder why it happens in this scope ("action" is not defined in any other way):

<html>
<head>
    <script type="text/javascript">
        function action() {
            alert('test');
        }
    </script>
</head>
<body>
    <form>
        <input type="button" value="click" onClick="action();">
    </form>
</body>
</html>
needfulthing
  • 1,056
  • 11
  • 21
  • 1
    _I am surprised there is no duplicate for this question_ – Rayon Jun 02 '16 at 11:20
  • That's the way inline event handlers work. See my answer here: http://stackoverflow.com/questions/6941483/onclick-vs-event-handler/21975639#21975639 – Felix Kling Jun 02 '16 at 13:37
  • @Rayon: this has been asked before, but I can imagine that it is difficult to name the question or what to look for without knowing what the issue is. I mean, the title of this question is not very indicative of the problem. – Felix Kling Jun 02 '16 at 13:42

1 Answers1

5

Inside the form, action is a string reference to the form action. If you change your onclick to alert(action) you will get the action of the form (which will be an empty string for your specific form).

In the same manner, form will be a reference to a form, and method will contain the form method, if you use them within the form. window.action will still refer to your function.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222