Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript onsubmit not working

Tags:

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>
like image 849
Stoffl Avatar asked Mar 22 '14 17:03

Stoffl


People also ask

Why my Onsubmit is not working?

To fix form onsubmit not working with JavaScript, we can set the form's onsubmit property to a function that's run when we click the submit button. to add a form. We add the submit button for the form with <input type="submit"> .

What is Onsubmit in JavaScript?

The onsubmit event is an event that occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the web server.

Why submit button is not working in HTML?

You need to ensure you have the submit button within the form element and an appropriate action attribute on the form element is present. For a more direct answer, provide the code you are working with.

How does Onsubmit form work?

The onsubmit event is performed the triggers is based upon the submit function whenever the client user request in the form-wise data is submitted to the server or the client request is supposed to be cancelled or aborted the submission of the datas in JavaScript. The method form.


1 Answers

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

like image 169
adeneo Avatar answered Sep 17 '22 14:09

adeneo