Skip to content

Instantly share code, notes, and snippets.

@rstackhouse
Last active December 20, 2015 05:59
Show Gist options
  • Save rstackhouse/6082575 to your computer and use it in GitHub Desktop.
Save rstackhouse/6082575 to your computer and use it in GitHub Desktop.
Open a hidden file input by clicking a button.
<html>
<head>
<title>Test upload form focused by button press</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<!--Some ideas on better styling methods at http://www.quirksmode.org/dom/inputfile.html-->
<input name="file" id="file" type="file" style="display:none;">
<button type="button" id="upload-button">Upload a file &hellip;</button>
<button type="button" id="cancel-button" style="display:none;">Cancel</button>
<script type="text/javascript">
"use strict";
$(document).ready(function () {
var defaultMsg = $('#upload-button').text();
$("#upload-button").click(function (event) {
if ($('#file').val() != '') {
alert('Pretend like we\'re uploading a file now');
}
else {
$(event.target).hide();
$('#file').show();
$('#file').click();
}
});
$("#file").change(function (event) {
var $target = $(event.target);
$target.hide();
var filename = $target.val();
var startIndex = (/\\/.test(filename) ? filename.lastIndexOf('\\') : filename.lastIndexOf('/') ) + 1;
filename = filename.substr(startIndex);
var $uploadButton = $('#upload-button');
var $cancelButton = $('#cancel-button');
if (filename.length && filename.length > 0) {
$uploadButton.text('Upload ' + filename);
$cancelButton.show();
}
else {
$uploadButton.text(defaultMsg);
$cancelButton.hide();
}
$uploadButton.show();
});
$("#cancel-button").click(function (event) {
$("#file").val('');
$("#file").hide();
$("#upload-button").text(defaultMsg);
$(event.target).hide();
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment