I'm trying to make a custom <input type="file">
button for a system, but the browser always gives me errors and when it doesn't, the button doesn't work as intended. I suspect I'm not using the escape operators correctly. Either that, or my UNIX environment is interfering with the correct functioning.
I've tried this in multiple ways, and have in mind the error is always the same: "Uncaught SyntaxError: Invalid or unexpected token".
fileName = e.target.value.split("\\").pop();
Throws out the error. This should be the correct code as it's what I'm trying to do;
fileName = e.target.value.split("\\\\").pop();
Doesn't throw an error, but makes the source code look like fileName = e.target.value.split("\\").pop();
. This doesn't work as intended as what I want is only one "\" backslash.
Code is as follows:
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple />
<label for="file"><span>Choose a file</span></label>
.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;
cursor: pointer;
}
.inputfile:focus + label,
.inputfile + label:hover {
background-color: red;
}
.inputfile:focus + label {
outline: 1px dotted #000;
outline: -webkit-focus-ring-color auto 5px;
}
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 = fileName ? fileName : labelVal;
});
});
What I'm trying to do is make the custom button change its innerHtml to the name of the file the user selected.
The JSFiddle works as intended with only two "\" backslashes. This is why I think UNIX is a suspect - "\" is also a special character, meaning a single-character quote. All web code runs inside this UNIX environment - we compile everything using it.
Any ideas or alternatives?