I am trying to use a code to change the style of the file
type buttons in html using CSS and JS. Somehow the JS function is not working properly and it is not replacing the name of the selected file on the label. Here are the codes in the jsfiddle: See the codes in jsfiddle
Any help is appreciated!
html:
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple />
<label for="file"><strong>Choose a file</strong></label>
css:
.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.inputfile + label {
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: black;
display: inline-block;
}
.inputfile:focus + label,
.inputfile + label:hover {
background-color: red;
}
.inputfile + label {
cursor: pointer; /* "hand" cursor */
}
js:
var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input )
{
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e )
{
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName )
label.querySelector( 'span' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});
There is no span tag inside your label
Change this
label.querySelector( 'span' ).innerHTML = fileName;
To this
label.querySelector( 'strong' ).innerHTML = fileName;