How to display file name for custom styled input file using jquery?

前端 未结 7 1304
我寻月下人不归
我寻月下人不归 2020-12-02 15:49

I have styled a file input using CSS:

相关标签:
7条回答
  • 2020-12-02 16:31

    You need to get name of file when input change and insert it into html. In the code this.files[0].name get name of selected file.

    $("#file-upload").change(function(){
      $("#file-name").text(this.files[0].name);
    });
    

    $("#file-upload").change(function(){
      $("#file-name").text(this.files[0].name);
    });
    .custom-file-upload {
        border: 1px solid #ccc;
        display: inline-block;
        padding: 6px 12px;
        cursor: pointer; 
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
        <label for="file-upload" class="custom-file-upload">
            <i class="fa fa-cloud-upload"></i> Upload Image
        </label>
        <input id="file-upload" name='upload_cont_img' type="file" style="display:none;">
        <label id="file-name"></label>
    </form>

    Also you can do this work using pure javascript

    document.querySelector("#file-upload").onchange = function(){
      document.querySelector("#file-name").textContent = this.files[0].name;
    }
    

    document.querySelector("#file-upload").onchange = function(){
      document.querySelector("#file-name").textContent = this.files[0].name;
    }
    .custom-file-upload {
      border: 1px solid #ccc;
      display: inline-block;
      padding: 6px 12px;
      cursor: pointer; 
    }
    <form>
      <label for="file-upload" class="custom-file-upload">
        <i class="fa fa-cloud-upload"></i> Upload Image
      </label>
      <input id="file-upload" name='upload_cont_img' type="file" style="display:none;">
      <label id="file-name"></label>
    </form>

    0 讨论(0)
提交回复
热议问题