javascript onsubmit not working

回眸只為那壹抹淺笑 提交于 2020-02-27 04:40:11

问题


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>

回答1:


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




回答2:


Add return statement in your code

<script>
function upload(){
    alert("I am an alert box!");
    return false;
}
</script>


来源:https://stackoverflow.com/questions/22581273/javascript-onsubmit-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!