sdfgg45 sdfgg45 - 2 months ago 5
jQuery Question

How to fill placeholder with filename from input field using jQuery?

Like the topic states, i want to get the filename of selected file, and then fill in the filename to the placeholder, i don’t want to use the class since this are being cloned dynamically as well.

I have made a attempt finding the closest element, with no success.
Could this be done using closest() / find() or prev()?

<div class="col-md-10">
<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-primary">
Browse <input class="documentation" type="file" name="documentation[]" >
</span>
</label>
<input value="" type="text" class="form-control file-placeholder" readonly>
</div>
</div>

<script>
$('.documentation').change(function () {
var filename = $(this).val();
$(this).closest('.file-placeholder').find('.file-placeholder').val(filename);
});
</script>

Answer

$(this).parent().parent().siblings('.file-placeholder') selector should be used to give selected filename as value to nearest text field.

$('.documentation').on('change',function () {
  var filename = $(this).val();
  $(this).parent().parent().siblings('.file-placeholder').val(filename);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-10">
  <div class="input-group">
    <label class="input-group-btn">
      <span class="btn btn-primary">
        Browse <input class="documentation" type="file" name="documentation[]" >
      </span>
    </label>
    <input value="" type="text" class="form-control file-placeholder" readonly>
  </div>
</div>

Comments