I have a file input that I have styled to be a custom button, but i’m not able to keep the upload image when the user uploads the file. It is replaced with the text of the file name but i would also like to keep the image. I know it is something simple but can’t seem to figure it out. here is the code:
HTML:
<div id="file"><img src="~/Images/choosefile.png" /></div>
<input type="file" name="file"/>
Javascript:
var wrapper = $('<div/>').css({ height: 0, width: 0, 'overflow': 'hidden' });
var fileInput = $(':file').wrap(wrapper);
fileInput.change(function () {
$this = $(this);
$('#file').text($this.val().substring(12, 75));
})
$('#file').click(function () {
fileInput.click();
}).show();
CSS:
`#file
{
display:none;
cursor: pointer;
}`
**Update – here is how it turned out if anyone would like to use it***
HTML:
<div id="file" style="margin-right:10px;"><img src="~/Images/choosefile.png" style="margin-bottom:-5px; padding-right:10px;"/><span style="border-left-width:10px;"></span></div>
<input type="file" name="file"/>
Javascript:
var wrapper = $('<div/>').css({ height: 0, width: 0, 'overflow': 'hidden' });
var fileInput = $(':file').wrap(wrapper);
fileInput.change(function () {
$this = $(this);
$('#file>span').text($this.val().substring(12, 75));
})
$('#file').click(function () {
fileInput.click();
}).show();
CSS:
`#file
{
display:none;
cursor: pointer;
}`
When you use .text() it is replacing your image with the value of the file input. I recommended adding a span inside your DIV and setting the value of the current input on it. It will be easier to separate and keep track of.
HTML
JQuery