David David - 6 months ago 14
jQuery Question

jQuery on not working on newly added child element

I have a couple selects set up, and added a way to add a new set of them. Works fine, except when I run the same "on" function again on the new element, it fires properly, but the child element is not changing.

$('body').on('change', '.select-funnel-process', function() {
var data = {
account: APP.account,
type: $('option:selected', this).val()
}

var selectDiv = $(this).parents('.funnel-group').find('.process-details')
//this doesn't work on the new elements

$.post(APP.api + 'get/get-data', data, function(res) {
var json = JSON.parse(res);
var result = json.result;

for (var p in result) {
//this doesn't work on the new elements
selectDiv.append('<option class="added_option" value="' + p + '">' + p + '</option>').prop('disabled', false)
}

selectDiv.select2();
//this doesn't work on the new elements
});
})


Is there a way to manually bind an event listener to a child element?
Strange that the initial select works on-change, but it's child element won't work.

I think it has something to do with the way I'm setting up
selectDiv


Here's the html that's added:

<div class="wrapper-class">
<div class="box box-default">
<div class="box-header with-border">
<h3 class="box-title"><i class="fa fa-bars"></i> Funnel Step <span class="funnel-step-id"></span></h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
<button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
</div><!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-12">
<form class="form-inline funnel-group">
<div class="form-group col-md-3">
<select class="form-control input-block-level select-funnel-process" name="properties">
<option selected="selected" disabled="disabled">Select a Process</option>
<option value="page">Page View</option>
<option value="event">Event</option>
</select>
</div>
<div class="form-group col-md-3">
<select class="form-control input-block-level process-details" name="properties" >
<option selected="selected" disabled="disabled">Select a Process First</option>
</select>
</div>
</form>


</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.box-body -->
</div>
</div>


Edit: solved

I was missing the class 'funnel-group' on the new DOM element, so using it as a selector was useless. Added it and it worked

Answer

So your selector was wrong. Change code to closest.

var selectDiv = ($(this)).closest('.funnel-group').find('.process-details')

    $('body').on('change', '.select-funnel-process', function() {
    var data = {
        type: $('option:selected', this).val()
    } 
    var selectDiv = ($(this)).closest('.funnel-group').find('.process-details')
    selectDiv.append('<option class="added_option" value="THOR"> THOR</option>').prop('disabled', false);

})

https://jsfiddle.net/3k33vunn/