Jquery trigger file input

2018-12-31 10:15发布

Am trying to trigger an upload box (browse button) using jQuery.
The method I have tried now is:

$('#fileinput').trigger('click');   

But it doesn't seem to work. Please help. Thank you.

19条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 10:34

You can use LABEL element ex.

<div>
    <label for="browse">Click Me</label>
    <input type="file" id="browse" name="browse" style="display: none">//
</div>

This will trigger the input file

查看更多
浮光初槿花落
3楼-- · 2018-12-31 10:34

Just for the sake of curiosity, you can do something like you want by dynamically creating an upload form and input file, without adding it to the DOM tree:

$('.your-button').on('click', function() {
    var uploadForm = document.createElement('form');
    var fileInput = uploadForm.appendChild(document.createElement('input'));

    fileInput.type = 'file';
    fileInput.name = 'images';
    fileInput.multiple = true;

    fileInput.click();
});

No need to add the uploadForm to the DOM.

查看更多
与君花间醉酒
4楼-- · 2018-12-31 10:38

Try this, it's a hack. the Position:absolute is for Chrome and trigger('change') is for IE.

var hiddenFile = $("<input type=\"file\" name=\"file\" id=\"file1\" style=\"position:absolute;left:-9999px\" />");
$('body').append(hiddenFile);

$('#aPhotoUpload').click(function () {
    hiddenFile.trigger('click');
    if ($.browser.msie)
        hiddenFile.trigger('change');
});

hiddenFile.change(function (e) {
    alert('TODO');
});
查看更多
深知你不懂我心
5楼-- · 2018-12-31 10:40

Actually, I found out a really easy method for this, which is:

$('#fileinput').show().trigger('click').hide();   

This way, your file input field can have the css property display on none and still win the trade :)

查看更多
皆成旧梦
6楼-- · 2018-12-31 10:40

Based on Guillaume Bodi's answer I did this:

$('.fileinputbar-button').on('click', function() {
    $('article.project_files > header, article.upload').show();
    $('article.project_files > header, article.upload header').addClass('active');
    $('.file_content, article.upload .content').show();
    $('.fileinput-button input').focus().click();
    $('.fileinput-button').hide();
});

which means it's hidden to start with and then displayed for the trigger, then hidden again immediately.

查看更多
大哥的爱人
7楼-- · 2018-12-31 10:41

That's on purpose and by design. It's a security issue.

查看更多
登录 后发表回答