raqulka raqulka - 4 months ago 7
jQuery Question

How to remove ajax appended container with data-id

I am adding a hidden fields with user selection so I can reinsert them later. Also I am adding a normal div, to show the user their selection.

I am trying to create a delete function, where the button will delete the visible row, as well as the hidden one.

Right now I am able to delete the correct visible row, but it won't delete the correct hidden div.

I have tried to get the

, but it always deletes the last one in the row, not the corresponding one.

How can I delete the correct div from
that corresponds to the one in

//nanny childcare ranges
$.each(data.nanny_age_range, function(index, data) {

var str = '<a href="#" id="' + data.nanny_age_range_id + '" aria-label="Close" class="deleteAge"><i class="fa fa-times" aria-hidden="true"></i></a>';

var hiddenAgeTo = '<input id="userProfileAgeTo' + childAgeCount + '" value="'+data.age_maximum+'" name="userProfileAgeTo[]" style="visibility:hidden; position:absolute;" type="text" />';

var hiddenAgeFrom = '<input id="userProfileAgeFrom' + childAgeCount + '" value="'+data.age_minimum+'" name="userProfileAgeFrom[]" style="visibility:hidden; position:absolute;" type="text" />';

var childAgeAppend =
' <div class="col-md-12" id="childAgeRange'+childAgeCount+'">'+
' <div class="col-md-3">'+
' <b>From'+data.age_minimum+' to '+data.age_maximum+'</b>'+
' </div>'+
' <div class="col-md-3">'+
' '+str+''+
' </div>'+
$("#hiddenChildAgeRanges").append('<div name="nanny_age_range_id[]" value="'+data.nanny_age_range_id+'" id="userAgeRangeSelection'+ childAgeCount+'" data-id="userAgeRangeSelection'+data.nanny_age_range_id+'">'+ hiddenAgeFrom + hiddenAgeTo+'');


//delete nanny age range
$(document).on("click", ".deleteAge", function(e) {
var age_id = $(this).attr('id');

$(this).closest('.col-md-12').fadeOut(300, function() {
type: "POST",
url: 'PHP/deleteData.php',
data: "age_id=" + age_id,
success: function(data) {
if (data.status == 'success') {
} else if (data.status == 'error') {
error: function(jqXHR, textStatus, errorThrown, data) {
console.log(jqXHR, textStatus, errorThrown, data);


As you are creating the hidden element using the nanny_age_range_id property which is also the ID attribute of deleteAge element. Create the selector and do the operation.

You can use Attribute Equals Selector [name=”value”] and the remove().

//delete nanny age range
$(document).on("click", ".deleteAge", function(e) {
    var age_id = $(this).attr('id');

    $('[data-id="userAgeRangeSelection' + age_id +'"]').remove();
    //Rest of the code