Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file name of image before upload - JQuery

I have a form to upload image with:

<div class="col-sm-4">
 <input id="file_input" type="file" style="visibility: hidden; width: 0; height: 0" name="image[photo_new]" accept="image/*">
</div>
<div class="col-lg-8">
  <div class="form-group row">
    <label class="col-sm-3 control-label" for="title">
      <label for="image_title">Title</label>
    </label>
    <div class="col-sm-9">
      <input id="title" class="form-control" type="text" placeholder="Title" name="image[title]" maxlength="200">
    </div>
  </div>
</div>

I want when users click to #input_file area to choose image, then the after choosing file, the file name will display immediately in #title field. For example name.png should be name. I want to use JQuery to do this function but don't know how, any advises? Thank in advance.

like image 505
DinhNgocHien Avatar asked Dec 19 '22 17:12

DinhNgocHien


1 Answers

You can use this.value to get the file value in a change event handler and then extract the name like

$('#file_input').change(function() {
  //$('#title').val(this.value ? this.value.match(/([\w-_]+)(?=\.)/)[0] : '');
  $('#title').val(this.files && this.files.length ? this.files[0].name.split('.')[0] : '');

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="file_input" type="file" />
<input id="title" />
like image 169
Arun P Johny Avatar answered Jan 08 '23 21:01

Arun P Johny