user3387113
user3387113

Reputation: 23

Display file name from input type file - console.log(fileName) return null

I'm trying to display file name from input type file.

This is my code:

<input id="id_file_field" name="file_field" type="file" style="display:none" />

Here jQuery:

$(document).ready(function () {
    $("#upload_file").click(function () {
        $("#id_file_field").trigger('click');
        var path = $("#id_file_field").val();
        var fileName = path.match(/[^\/\\]+$/);
        console.log(fileName);
    });
});

Why console.log(fileName) return null?

Upvotes: 1

Views: 5238

Answers (2)

H&#252;seyin BABAL
H&#252;seyin BABAL

Reputation: 15550

You can use following js;

$("#upload_file").click(function () {
        $("#id_file_field").trigger('click');
    });

    $('#id_file_field').change(function () {
        var value = $(this).val();
        var name = value.split(/[\\/]/);
        console.log(name[name.length - 1]);
    });

Here is a working fiddle: http://jsfiddle.net/cubuzoa/BKuLT/3/

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388436

You need to wait for the change event

$(document).ready(function () {
    $("#upload_file").click(function () {
        $("#id_file_field").trigger('click');
    });
    $('#id_file_field').change(function () {
        var value = this.value;
        var fileName = typeof value == 'string' ? value.match(/[^\/\\]+$/)[0] : value[0]
        console.log(fileName);
    })
});

Demo: Fiddle

Upvotes: 4

Related Questions