使用jQuery从输入[type =’file’]获取文件名

前端之家收集整理的这篇文章主要介绍了使用jQuery从输入[type =’file’]获取文件名前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是上传的表单。
  1. <form class="alert alert-info">
  2. <div>
  3. <b id = "select_file" class="span3" style="font-weight: bold; cursor: pointer; ">Please select image</b>
  4. <input class="span3" type="file" name="image_file" id="image_file" style="display:none " />
  5. <input disabled="true" type="button" value="Upload image" class="btn" />
  6. </div>
  7. </form>

我使用以下脚本打开一个带有文件的窗口。我想在< b id ='select_file'>中显示文件名。

我如何做到这一点?

  1. $('#select_file').click(function(){
  2. var _this = $(this);
  3. $('#image_file').show().focus().click().hide();
  4.  
  5. var filename = $('#image_file').val();
  6. _this.html(filename);
  7.  
  8. $('.btn').attr('disabled',false);
  9. });

解决方法

你必须对输入类型文件的change事件这样做:
  1. $('#select_file').click(function() {
  2. $('#image_file').show();
  3. $('.btn').prop('disabled',false);
  4. $('#image_file').change(function() {
  5. var filename = $('#image_file').val();
  6. $('#select_file').html(filename);
  7. });
  8. });​

猜你在找的jQuery相关文章