0

我有一个表单,我在其中使用 JQuery 表单插件上传文件。我想自定义上传按钮并让它提交 onchange。您可以在下面看到我隐藏了表单并将其替换为#upfile1 链接。

<form id="dataform" action="submit" method="post" enctype="multipart/form-data">
    <a href="#" id="upfile1">Import .csv</a>
    <input type="file" name="myfile" id="myFile" style="display:none" onchange='this.form.submit()'/>
</form>

然后在我的 JQuery 中,我用这个模拟点击表单:

$("#upfile1").click(function () {
    $("#myFile").trigger('click');
});

但是,将其与 JQuery Form Plugin 混合似乎不起作用。该页面再次加载,并在 URL 的末尾添加了“/submit”。

这是表单插件中的 JQuery:

(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('#dataform').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    success: function(data) {
        var percentVal = '100%';
        bar.width(percentVal)
        percent.html(percentVal);

       //Do some stuff

    },
complete: function(xhr) {
    status.html(xhr.responseText);
}
//
}); 
return false;
})();
4

1 回答 1

1

您必须提交表单,而不是输入。尝试这个:

$("#upfile1").click(function (e) {
    e.preventDefault();
    $("#dataform").submit();
});

可以在此处找到 jQuery 提交的文档。

我更好地理解你的问题,很抱歉造成混乱!的HTML:

<input type="file" id="fileInput" multiple>
<button id="fileButton">Select some files</button>

jQuery:

document.querySelector('#fileButton').addEventListener('click', function(e) {
    // Use the native click() of the file input.
    document.querySelector('#fileInput').click();
}, false);

CSS:

#fileInput { visibility:hidden; }

小提琴。_

显然,添加您想要使它看起来不错的样式。

于 2013-10-26T01:46:51.567 回答