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 y开发者_Go百科et.
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.
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.
Try using trigger()
:
$(this).parents(".formFile").find("input[type='file']").trigger('click');
精彩评论