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
1 Answer
Reset to default 5You 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">