Reputation: 23
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
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
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