如何使用jquery显示自定义样式的输入文件的文件名? [英] How to display file name for custom styled input file using jquery?

查看:157
本文介绍了如何使用jquery显示自定义样式的输入文件的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用CSS设计了一个文件输入:

.custom-css =>

< form> < label for =file-uploadclass =custom-file-upload> < i class =fa fa-cloud-upload>< / i>上传图片< / label> < input id =file-uploadname ='upload_cont_img'type =filestyle =display:none;>< / form>



一切正常,但我想显示选定的文件名称。如何使用CSS或jQuery来实现这一点?

解决方案

您必须绑定并触发 [type = file] 元素并读取文件名称为:

  $('#file-upload')。change(function(){var i = $(this).prev('label')。clone(); var file = $('#file-上传')[0] .files [0] .name; $(this).prev('label')。text(file);});  

  .custom-file-upload {border:1px solid #ccc;显示:inline-block; padding:6px 12px; cursor:pointer;}  

< script src =https ://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< /脚本><形式> < label for =file-uploadclass =custom-file-upload> < i class =fa fa-cloud-upload>< / i>上传图片< / label> < input id =file-uploadname ='upload_cont_img'type =filestyle =display:none;>< / form>


I have styled a file input using CSS:

.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;">
</form>  

Everything is working fine, but I’d like to display the selected file name. How is this possible using CSS or jQuery?

解决方案

You have to bind and trigger the change event on the [type=file] element and read the files name as:

$('#file-upload').change(function() {
  var i = $(this).prev('label').clone();
  var file = $('#file-upload')[0].files[0].name;
  $(this).prev('label').text(file);
});

.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;">
</form>

这篇关于如何使用jquery显示自定义样式的输入文件的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆