I have the following ajax query which returns html elements and places them inside a bootstrap modal:
$.get("ajax.parser.php?ajax_request=manageidentifiedcontact", function(data){
$('#indentified-modal').html(data);
$('#IdentifiedModal').modal('show');
});
I also have the following script to append a button to an element, whether it is contained on the static page or whether it arrives after an ajax query.
var newContactButton = '<span class="quick-add-contact input-group-addon"><a class="quick-add-contact-link" href="contact_update.php"><i class="fa fa-user-plus"></i> Add</a></span>';
$('.typeahead-field').append(newContactButton);
$(document).ajaxComplete(function() {
$('.typeahead-field').each(function() {
if (!$(this).find('.quick-add-contact').length) {
$(this).append(newContactButton);
}
});
});
The button is appended properly in both cases as intended. The error that I now have is listening to an onclick event on the appended button.
var oldModalId = false;
var closestValueId = false;
var closestContactNameId = false;
$('.quick-add-contact').on('click', 'a', function (e) {
e.stopPropagation();
e.preventDefault();
if ($('div.modal.in').attr('id') != 'quick-add-contact-modal') {
if($('div.modal.in').length) {
oldModalId = $('div.modal.in').attr('id');
$('#'+oldModalId).modal('hide');
}
closestValueId = $(this).closest('.typeahead-field').find('input[type="hidden"]').attr('id');
closestContactNameId = $(this).closest('.typeahead-field').find('input[type="text"]').attr('id');
$('#quick-add-contact-modal').modal('show');
}
});
This last snippet correctly fires for the buttons that were appended on the static page, but it does not work for the button that was appended after the ajax query.
Everything I read online suggests .on is the correct method, but for some reason it doesn't work in this case and I can't figure out why.
Any help appreciated.
EDIT :
I have also tried to use
$(document).on('click', '.quick-add-contact a', function (e) {
});
Works on none of the elements :
$(document).on('click', '.quick-add-contact-link', function (e) {
});
Works on none of the elements :
$(document).on('click', 'a', function (e) {
});
Works on all of my static 'a' elements, but none of the dynamically added ones.