21

I am trying to make a javascript function work on submitting the form, the function doesnt seem to run. Can anyone help?

<html>
<head>
    <script>
        function upload(){
                alert("I am an alert box!");
        }
     </script>
</head>
<body>
    <form enctype="multipart/form-data" method="post" onsubmit="return upload();">
    <input type="file" name="file">
    <input type="submit" name="upload" value="Datei hochladen">
    </form>
</body>
</html>
Stoffl
  • 525
  • 2
  • 4
  • 12

3 Answers3

33

When attaching the event handler to the form element, the scope of the event handler is the form and not the window

<form enctype="multipart/form-data" method="post" onsubmit="return upload(this);">

<script>
    function upload(scope) {
        console.log(scope); // The passed scope from the event handler is
    }                       // the form, and not window
</script>

As input elements inside a form are attached as properties to the form object, where the name is the key, calling upload() in the event handler, where the scope is the form, would equal calling form.upload(), but the form already has an element with that name so form.upload is the upload button, not the upload() function in the global scope.

To solve it, either rename the function or the element

<html>
<head>
    <script>
        function upload(){
                alert("I am an alert box!");
        }
     </script>
</head>
<body>
    <form enctype="multipart/form-data" method="post" onsubmit="return upload();">
    <input type="file" name="file">
    <input type="submit" name="upload2" value="Datei hochladen">
    </form>
</body>
</html>

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    Actually the problem is not with the a global variable. Usually only for elements with IDs a global variable is created. In this case I believe the properties of the form element are also in the scope of the event handler, so `upload` refers to `form.upload`. – Felix Kling Mar 22 '14 at 18:18
  • 1
    @FelixKling - You're right, `window.upload` is still the function, it's `form.upload` that causes the issue, or in that scope just `upload`. If I do `onsubmit="window.upload()"` it works. I'll edit the answer. – adeneo Mar 22 '14 at 18:26
  • the only thing that actually worked for me was using javascript declaration. no idea why, but looks like there's more to this. – cregox Sep 30 '20 at 01:25
1

My problem, I had without knowing a form inside a form I was interacting with the inner one no matter what I do the outer form always executes

Fathy
  • 377
  • 5
  • 13
-4

Add return statement in your code

<script>
function upload(){
    alert("I am an alert box!");
    return false;
}
</script>
N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32
NAW_AB
  • 23
  • 1
  • 3