Reputation: 33
I have a standard input field:
<input type="file">
in my form, but I have it hidden so that I can use my own image for the button (as seen in many answers on stackoverflow)
But when using this method, there's no confirmation given to the user that their file was selected, because the standard input box is hidden and so they never see the filename.
So my question boils down to this: How can I detect that a file has been selected, and then display something on the page (not an alert box)? Ideally I just want to show a little icon or some text saying "file selected".
Jquery is fine but if there's a way to do this without it, I'd much prefer that. Thanks!
Upvotes: 1
Views: 4134
Reputation: 66
This is the Code which you are looking. For better UI Performance, look on Internet Explorer 8+
HTML and JavaScript:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>File Picker</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function fileValidator()
{
var fileName=document.forms["FileForm"]["fileName"].value.replace("C:\\fakepath\\", "");
var response=confirm("Are you sure to Upload '"+fileName+"'?");
console.log(response);
if(response==false)
{
document.forms["FileForm"]["fileName"].value="";
}
}
</script>
</head>
<body>
<form name="FileForm" action="" method="Post">
<table>
<tr>
<td><input type="file" name="fileName" onchange="fileValidator();"/></td>
</tr>
<tr>
<td><input type="submit" value="Upload"/></td>
</tr>
</table>
</form>
</body>
</html>
Upvotes: 0
Reputation: 2191
This is a pretty easy way to do it without using Jquery. You will have to change the id's to match your html of course.
Here is a link to a jsfiddle example: http://jsfiddle.net/larryjoelane/rrns0k4e/1/
HTML Part:
<input id="file-select" type="file">
<div id="file-selected"></div>
Javascript Part:
//on change event listener for #file-select
document.getElementById("file-select").onchange = function() {
//call getFileSelected method
getFileSelected();
};
function getFileSelected(){
//get the value of the input file element
var getFileSelected = document.getElementById("file-select").value;
//display the results of the input file element
//you can append something before the getFileSelected value below
//like an image tag for your icon or a string saying "file selected:"
//for example.
document.getElementById("file-selected").innerHTML = getFileSelected;
}
Upvotes: 6
Reputation: 380
If you listen to the change event on the element, you'll know when a file have been selected:
$('input').change(function(){
console.log($(this).val());
});
You can use $(this).val()
, if you want to show the filename. If you don't want to use jQuery, you're looking for the onchange
event.
Fiddle: http://jsfiddle.net/cphutg90/
Upvotes: 1