DinhNgocHien DinhNgocHien - 2 years ago 69
Javascript Question

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 class="col-lg-8">
<div class="form-group row">
<label class="col-sm-3 control-label" for="title">
<label for="image_title">Title</label>
<div class="col-sm-9">
<input id="title" class="form-control" type="text" placeholder="Title" name="image[title]" maxlength="200">

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

Answer Source

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" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download