slash89mf slash89mf - 2 months ago 7
HTML Question

Select div using jquery not working

I have an event listener on dynamically created elements:

<script>
$(document).on('change', '.inputfile', function() {
var name = ($(this).val().split('\\').pop());
selectFile(name);
});
</script>


Once file is selected, i would like to append a paragraph showing the filename itself. My problem is that jquery selector is not working:

function selectFile(filename) {
alert(filename);
var classes = $(this).closest('.inputgroup');
$('classes').append('<p>'+filename+'</p>');
}


I would like to append the paragraph in the nearest div with class=inputgroup, because there are several div with that class.
Using a simple
$('.inputgroup').append('<p>'+filename+'</p>');
is ok and paragraph is created.
This is the HTML:

<div class="inputgroup">
<label class="btn btn-default btn-info" style="margin-top: 8px">
Browse <input type="file" style="display: none;" class="inputfile"/>
</label>
<button type="button" class="btn btn-outline-danger" onclick="myAjax()">Ok</button>
<span id="remove_field" class="glyphicon glyphicon-remove" aria-hidden="true" style="vertical-align: middle"></span>
</div>

Answer

This line

$('classes').append('<p>'+filename+'</p>');

Is searching for an element named "classes" - that's not a valid HTML element.

I think you wanted

$(this).closest('.inputgroup').append('<p>'+filename+'</p>');

Based on this line of your question

I would like to append the paragraph in the nearest div with class=inputgroup

But you should put this straight in the event handler, otherwise this has a different meaning

$(document).on('change', '.inputfile', function() {
    var name = ($(this).val().split('\\').pop());
    $(this).closest('.inputgroup').append('<p>'+name+'</p>');
});
Comments