0

enter image description here

I'm trying to get the file through input. I hide the input through CSS and gave the label a style. There is a problem here.

If input is hidden, the default input button cannot support the supported get file name. I guess Vanila JS can solve this, but I don't know what to do. I tried to get the value value of the file and put it in the box specified as inner HTML, but it didn't work.

.submit{
   width:140px;
   height:40px;
   background-color:red;
   color:#fff;
   text-align:center;
   padding:10px;
   line-height:40px;
   cursor:pointer;
}
<input type="file" id="test" style="display:none;">
<label for="test">
    <span class="submit">submit</span>
    <span id="test2">filename</span>
</label>

3

2 Answers 2

1

Following this Answer, you can get the file name, and use innerHTML to show it to user.

document.getElementById('test').addEventListener("change", function() {
  var fullPath = document.getElementById('test').value;
  if (fullPath) {
    var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
    var filename = fullPath.substring(startIndex);
    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
      filename = filename.substring(1);
    }
    document.getElementById("test2").innerHTML = filename;;
  }
});
.submit {
  width: 140px;
  height: 40px;
  background-color: red;
  color: #fff;
  text-align: center;
  padding: 10px;
  line-height: 40px;
  cursor: pointer;
}
<input type="file" id="test" style="display:none;">
<label for="test">
    <span class="submit">submit</span>
    <span id="test2">filename</span>
</label>

Sign up to request clarification or add additional context in comments.

Comments

0

Your HTML

<input type="file" id="test" style="display:none;">
<label for="test">
    <span class="submit">submit</span>
    <span id="test2">filename</span>
</label>

Your CSS

.submit{
   width:140px;
   height:40px;
   background-color:red;
   color:#fff;
   text-align:center;
   padding:10px;
   line-height:40px;
   cursor:pointer;
 }

And Javascript

let file = document.querySelector('#test');
let test2 = document.querySelector('#test2');

file.addEventListener('change', function(e){
  test2.innerHTML = e.target.files[0].name;
});

Demo here https://jsfiddle.net/jozsefk/4gwzrj38/

Comments

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.