Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross browser open file browse dialog

I've been looking for that holy grail - nice file dialogs in HTML. I've come up with a solution that uses jQuery to click() the (hidden) file element when a button is clicked. This works fine in FireFox 4, but Chrome and Opera fail. Changing the click() to focus() worked for Chrome, but nothing in Opera works. I haven't tested IE, but I don't want to ragequit life quite yet.

Here is the current code:

HTML

<div class="formFile" id="profileImgContainer">
    <input type="file" name="profileImg" id="profileImg">

    <label>Profile Picture</label>

    <div>
        <input type="text" id="profileImgText"><input type="button" id="profileImgButton" value="Choose File">
    </div>
</div>

jQuery

$(".formFile input[type='file']").live('change', function()
{
    $(this).parents(".formFile").find("input[type='text']").val($(this).val());
});

$(".formFile input[type='button']").live('click', function()
{
    $(this).parents(".formFile").find("input[type='file']").click();
});

$(".formFile input[type='text']").live('click', function()
{
    $(this).parents(".formFile").find("input[type='file']").click();
});

Can anyone offer a cross browser way of opening the file dialog using jQuery/JavaScript? I don't want to use the transparent element trick due to the need to have input interactions (CSS :hover) etc.

like image 243
Bojangles Avatar asked Feb 23 '23 19:02

Bojangles


2 Answers

This might be some years late, but here's is a way of doing it without any Javascript and it's also cross browser.

<label>
  Open file dialog
  <input type="file" style="display: none">
</label>

In case you find problems, you may need to use the for attribute in the label pointing to the id of the input.

like image 115
JP de la Torre Avatar answered Feb 26 '23 07:02

JP de la Torre


Try using trigger():

$(this).parents(".formFile").find("input[type='file']").trigger('click');
like image 28
Naftali Avatar answered Feb 26 '23 07:02

Naftali