- Change default text in input type=”file”
- Change language of input type=file
HTML form input type=”file” provides “Browse” and “No file Selected” in firefox and “choose File” and “No File Chosen” in chrome to choose a file.
It’s not possible to translate “Choose file” and “No file chosen” or “Browse” and “No file selected” labels, as those are native browser elements and depend on browser’s language.
However, we can apply some tricks like
- Putting image instead of button
- Making file input transparent or display none
- Text input below the button
Trick with CSS
Trick with Javascript
HTML:
For image, file and video. You can use one as per requirement.
<!-- bootstrap.min.css not necessary --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.0/css/bootstrap.min.css"> <input data-com="fileBtn" placeholder="Select Image"> <!-- com: components --> <input data-com="fileBtn" placeholder="Select File"> <div class="mt-2"> <input id="build-by-myself" placeholder="Select Video" accept="video/mp4, video/webm"> <div>
Javascript:
<script>
// ? Test
(()=>{
window.onload = () =>{
// FileButton.className =”btn btn-danger”
FileButton.BuildAll() // auto build all data-com=”fileBtn”
// or you can specify the target that you wanted.
new FileButton(document.getElementById(“build-by-myself”), “btn btn-danger”)
}
})()
// ? script begin
class FileButton {
static className = “btn btn-primary”
static BuildAll() {
document.querySelectorAll(`input[data-com=”fileBtn”]`).forEach(input=>{
new FileButton(input, FileButton.className)
})
}
/**
* @param {HTMLInputElement} input
* @param {string} btnClsName
* */
constructor(input, btnClsName) {
input.style.display = “none” // [display is better than visibility](https://stackoverflow.com/a/48495293/9935654)
input.type = “file”
const frag = document.createRange().createContextualFragment(`<button class=”${btnClsName}”>${input.placeholder}</button>`)
const button = frag.querySelector(`button`)
input.parentNode.insertBefore(frag, input)
button.onclick = ()=>{
input.click()
}
input.addEventListener(`change`, (e)=>{
// create a textNode to show the file name.
const file = input.files[0]
if (file === undefined) {
return
}
const textNode = document.createTextNode(file.name)
if (button.textNode) { // create a new attribute to record previous data.
button.textNode.remove()
}
button.textNode = textNode
button.parentNode.insertBefore(textNode, input)
})
}
}
</script>