Jakob
Jakob

Reputation: 25

Style input Type="file" - filename javascript-solution do not work

I need a nice looking "uploadbutton" for a project and found a styling solution on the web: https://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/ It works fine so far, but I can't get the java script to run.

HTML:

<input type="file" name="file" id="file" class="inputfile" />
<label for="file">Choose a file</label>

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;
    });
});

I also tried it in jsfiddle and hade also no success so far (https://jsfiddle.net/LLpd1vev/1/). I took the code as ist was on the website since I have no experience at all with js.

As ist has shown is the filename quite critical for usability, got lot of questions because it isn't there.

Every help is appreciated - thanx in advanced!

Upvotes: 1

Views: 488

Answers (1)

Lennart
Lennart

Reputation: 1560

You're almost there. Your JS is working as it should, the reason you're not receiving a message is in your final part of your code;

if( fileName )
    label.querySelector( 'span' ).innerHTML = fileName;
else
    label.innerHTML = labelVal;

Here the code is checking to see if the variable fileName is populated and if it is, it looks for a span element within your label element. Since this isn't present in your HTML, javascript just chucks an error out (this can be checked using the console in chrome). Your HTML should look like this;

<input type="file" name="file" id="file" class="inputfile" />
<label for="file"><span>Choose a file</span></label>

Here's an updated JSFiddle of this issue fixed!

Upvotes: 1

Related Questions