4

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.

Bojangles
  • 99,427
  • 50
  • 170
  • 208
  • 1
    +1 for `I don't want to ragequit life quite yet` :-) – andyb Jun 23 '11 at 20:28
  • Thanks andyb. IE is the bane of my existence. If it went into a hole and died (or was replaced by FF, Chrome, sausages on a plate, etc) then I and every other web developer out there would be so much happier! – Bojangles Jun 23 '11 at 20:35
  • 1
    could not agree more! BTW, have you seen http://stackoverflow.com/questions/210643/in-javascript-can-i-make-a-click-event-fire-programmatically-for-a-file-input-e/3030174#3030174 – andyb Jun 23 '11 at 20:38
  • I just closed another tab with that in it, so I'll say yes ;-) I'm having a read now. – Bojangles Jun 23 '11 at 20:41

2 Answers2

5

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.

JP de la Torre
  • 1,593
  • 18
  • 20
3

Try using trigger():

$(this).parents(".formFile").find("input[type='file']").trigger('click');
Naftali
  • 144,921
  • 39
  • 244
  • 303