按钮onclick:“不是函数”,当表单的一部分时

时间:2018-08-22 15:38:54

标签: javascript jquery

我想在单击按钮时运行一些JavaScript,这将在uploadfile()函数中提供,例如:

<input type = "submit" class="btn btn-info" button id="uploadfile" onclick="uploadfile()">

这很好用(调用uploadfile()函数)。但是,如果此按钮是表单的一部分,则如下所示:

<form action = "http://localhost/uploaded" method = "POST" 
            enctype = "multipart/form-data">
            <input type = "file" name = "file" class="form-control-file">
            <input type = "submit" class="btn btn-info" value="Upload Image" button id="uploadfile" onclick="uploadfile()">
            </form>

我得到了错误:

  

未捕获的TypeError:uploadfile不是函数

1 个答案:

答案 0 :(得分:0)

onclick在表单内无法使用,请参见onClick event doesn't work inside form tag。解决方案是使用onsubmit,例如:

<form action = "http://localhost/uploaded" method = "POST" onsubmit="uploadfile()"
            enctype = "multipart/form-data">
            <input type = "file" name = "file" class="form-control-file">
            <input type = "submit" class="btn btn-info" value="Upload Image">
            </form>