Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input type=file attached to an onclick event

I have a menu like this:

<ul class="sub">
    <li><a href="#">New</a></li>
    <li><a href="#">Open</a></li>
    <li><a href="#">Save</a></li>
    <li><a href="#">Help</a></li>
</ul>

and I'd like to attach an onclick even to the Open li that would kick off a file open dialog, like input type="file" does. I can handle attaching code to the li's onclick event, but I don't know what code to attach.

TIA

like image 743
davej Avatar asked Oct 26 '25 01:10

davej


1 Answers

You can add a normal input type="file" to the page and style it to be hidden. Something like this:

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

(Only using in-line styling for this example, I recommend separating the style from the markup of course.)

Then you can initiate a click on it in response to a click event on the target element. With jQuery (assuming you can set an id on the li, or otherwise uniquely identify it in the selector in some way) it would be something like:

$('#clickableLiElement').click(function() {
    $('#theFileInput').click();
});

The input type="file" is still there and can be interacted with just like any other form element. It's just invisible to the user. But this would launch the Open File dialog and set its value to the element normally, which can be included in the POST to the server normally.

like image 195
David Avatar answered Oct 27 '25 15:10

David