0

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;
    });
});
1
  • 1
    There is error in console for line label.querySelector( 'span' ).innerHTML = fileName;. As there is no span element in your HTML. Commented Sep 24, 2017 at 10:00

1 Answer 1

1

There is no span tag inside your label

Change this

label.querySelector( 'span' ).innerHTML = fileName;

To this

label.querySelector( 'strong' ).innerHTML = fileName;
Sign up to request clarification or add additional context in comments.

1 Comment

Here is the codepen link for the same. codepen.io/rachitgulati26/pen/PJbjPE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.