最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get file name from file upload using jquery and set filename to a text field - Stack Overflow

programmeradmin0浏览0评论

I have to get filename of the uploaded file and set it to the textfield

I have done as follows

<input type="file" name = "filename" id="upload">
<input type="text" name = "file" id="file">

//jquery

$('#upload').change(function() {
    var filename = $('input[type=file]').val().split('\\').pop();
    var lastIndex = filename.lastIndexOf("\\");
    $('#file').val(filename);
});

and also tried this

$('#upload').change(function() {
    var filename = $(this).val();
    var lastIndex = filename.lastIndexOf("\\");
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex + 1);
    }
    $('#file').val(filename);
});

but filename is not displayed in the textfield.

I have to get filename of the uploaded file and set it to the textfield

I have done as follows

<input type="file" name = "filename" id="upload">
<input type="text" name = "file" id="file">

//jquery

$('#upload').change(function() {
    var filename = $('input[type=file]').val().split('\\').pop();
    var lastIndex = filename.lastIndexOf("\\");
    $('#file').val(filename);
});

and also tried this

$('#upload').change(function() {
    var filename = $(this).val();
    var lastIndex = filename.lastIndexOf("\\");
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex + 1);
    }
    $('#file').val(filename);
});

but filename is not displayed in the textfield.

Share Improve this question edited Jan 7, 2016 at 16:45 glw 1,6641 gold badge16 silver badges21 bronze badges asked Jan 7, 2016 at 15:25 RohinRohin 5263 gold badges8 silver badges20 bronze badges 5
  • 1 What do you mean by not working? – Perdomoff Commented Jan 7, 2016 at 15:37
  • filename is not displayed in the textfield – Rohin Commented Jan 7, 2016 at 15:51
  • 1 works fine for me jsbin./yuyuriqevi/1/edit?html,js,output – tkay Commented Jan 7, 2016 at 15:58
  • but not for me. Is there is anything wrong? – Rohin Commented Jan 7, 2016 at 16:01
  • @Rohin check my answer. – tkay Commented Jan 7, 2016 at 16:05
Add a ment  | 

1 Answer 1

Reset to default 5

You are supposed to be using jquery inside document ready. You might have forgotten to add that. Here is the working code.

      $(document).ready(function() {

    $('#upload').change(function() {
       var filename = $('input[type=file]').val().split('\\').pop();
      console.log(filename,$('#file'));
        var lastIndex = filename.lastIndexOf("\\");   
        $('#file').val(filename);
    });
      });
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="file" name = "filename" id="upload">
                                <input type="text" name = "file" id="file">

发布评论

评论列表(0)

  1. 暂无评论