File dialog from JavaScript *without* <input>

I am adding file import functionality to an existing page.

I want to do this using javascript and without modifying the page, ie. without adding the "input type="file" " tag, everyone seems to be talking about.

I have added the button, now I want the event to show the file dialog, user to browse for file and javascript to submit file to server for validation.

How do I do that? Btw, main priority is opening file dialog, so no need for user or submitting part, if you don't know it.

Thx

Answers:

Answer

Well, if I understand correct what you want, is some like this...

<input type="button" value="Add File" onclick="document.getElementById('file').click()" />
<input type="file" id="file" style="display:none" />

Hidding the file object and calling the file dialog with another object. Right ?

EDIT: Only Javascript

onclick="var f=document.createElement('input');f.style.display='none';f.type='file';f.name='file';document.getElementById('yourformhere').appendChild(f);f.click();"

Put this in your object with the id of your form in place of yourformhere !!

Answer

Here's is a way of doing it without any Javascript and it's also compatible with every browser, including mobile.


BTW, in Safari, the input gets disabled when hidden with display: none. A better approach would be to use position: fixed; top: -100em.


<label>
  Open file dialog
  <input type="file" style="position: fixed; top: -100em">
</label>

If you prefer you can go the "correct way" by using for in the label pointing to the id of the input like this:

<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">
Answer

I hid my first button like this

<input style="display:none;" type="file" id="file" name="file"/>

The following triggers the input file:

<i class="fa fa-camera-retro fa-3x" type="button" data-toggle="tooltip" title="Escoje tu foto de perfil" id="secondbutton" ></i> (i used an icon)

Which triggers my second button:

$( "#secondbutton" ).click(function() {
        $( "#file" ).click();
});

From http://api.jquery.com/click/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.