简体   繁体   中英

Triggering an html file upload text field?

I've stumbled across some code that works in Firefox but not Chrome.

What seems to be happening is that there is a file upload textfield that is sized in CSS. There is also an Upload button immediately to its right for the user to click to open a dialog to select a file. The textfield length is 60, which I think is used to overlay the "Upload" button and not size the field. I've reduced 60 to 50 in Firebug and it stops working.

How can I invoke the file upload dialog from the Upload button? I think I need to send some sort of click event to the textfield.

File: __________________ Upload   | Clicking field or Button opens file dialog

I've extracted the HTML:

<input name="fileField" id="fileField" type="file" size="60">
<span><input type="text" id="fileUploadField"><span></span></span>
<a href="javascript://" class="button" id="uploadButton"><span class="action">Upload</span></a>

The following should work for you:

document.getElementById('uploadButton').addEventListener('click', function(){
    document.getElementById('fileField').click();

    return false;
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM