I have number of forms on a page and each one has a file input. When the user chooses a file, I would like to print the name of the selected file in the <span class="fileNameBox"></span>
that is inside the relevant form.
Instead of input field for the file uploader, I'm using image "photoIconOn.png".
Why does it always print the file's name in the first form / class="fileNameBox" ?
JS:
<script>
$(function() {
$('input.file-field').on('change', function(e) {
var files = this.files,
filename = files[0].name;
$(this).closest('form').find('.fileNameBox').html(filename);
});
});
</script>
HTML:
<div class="form-group">
<label class="col-xs-2 control-label" >????</label>
<div class="col-md-8 col-xs-12">
<textarea class="form-control comment-field" name="comment[text]" rows="1" ></textarea>
<span class="fileNameBox"></span>
<input type='file' name='file[]' class=' form-control file-field hideBox' maxlength='1' accept='gif|jpg|png|bmp' id="uploadFile" style="display: none"/>
</div>
<label class="col-md-1 col-xs-1 control-label" for="uploadFile">
<img src="images/photoIconOn.png" alt="" class="uploadFileImg"/>
</label>
</div>
<div class="form-group">
<label class="col-xs-2 control-label" for="textinput"></label>
<div class="col-md-8 col-xs-12">
<button class="btn btn-primary submit" >SEND</button>
</div>
</div>
</form>
<form class="form-horizontal" action='#' method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="col-xs-2 control-label" >????</label>
<div class="col-md-8 col-xs-12">
<textarea class="form-control comment-field" name="comment[text]" rows="1" ></textarea>
<span class="fileNameBox"></span>
<input type='file' name='file[]' class=' form-control file-field hideBox' maxlength='1' accept='gif|jpg|png|bmp' id="uploadFile" style="display: none"/>
</div>
<label class="col-md-1 col-xs-1 control-label" for="uploadFile">
<img src="images/photoIconOn.png" alt="" class="uploadFileImg"/>
</label>
</div>
<div class="form-group">
<label class="col-xs-2 control-label" for="textinput"></label>
<div class="col-md-8 col-xs-12">
<button class="btn btn-primary submit" >SEND</button>
</div>
</div>
</form>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…