I am making an Ajax call and thus returning new entries to a table. So far so good, but I want to make a .prepend()
by adding a "Remove" button on each element in the list.
The problem is that this button
is only added in the first li
I tried to run jsFiddle but I can not do it. So I tried to post the code below in simplified form:
The flow is simple:
- Client clicks a button to add a new user;
- A Modal is opened with some fields;
- As soon as the Submit is given, I make an Ajax call by sending the values;
- A JSON is returned, which contains a result that I will add to a list on the screen;
Problem
- I make
$().each()
followed byif
to check if my remove button already exists on that line; - It just adds the button to the first record.
Code
$('#modal-form').submit(function(e) {
var url = "${pageContext.request.contextPath}/auth/addPassenger?${_csrf.parameterName}=${_csrf.token}";
$.ajax({
type: "POST",
url: url,
data: $("#modal-form").serialize(),
success: function(jsonData) {
if (jsonData != "") {
var passenger = jsonData.firstName;
$('#passenger-list').append('<li id="list-all-passenger" ><label>' + passenger + '</label></li>');
$('#passenger-list li').each(function(i) {
if (this, $('#button-cancel-passenger').length) {
} else {
$(this).prepend('<button id="button-cancel-passenger" type="reset" class="btn btn-danger pull-right" style="position: relative; top: -1px;"><span class="entypo-cancel-squared"></span> Remover</button>');
}
});
$('#myModal').modal('hide');
$('#passenger-name').val('');
$('#passenger-lastName').val('');
$('#passenger-email').val('');
$('#passenger-phone').val('');
$('#passenger-birth').val('');
$('#passenger-rg').val('');
$('#passenger-cpf').val('');
} else {
if ($('#div-error-passenger').length) {
return false;
} else {
$('#div-modal-input-body').prepend('<div id="div-error-passenger" class="alert alert-info box03"></div>');
$('#div-error-passenger').append('<span id="span-error-passenger" class="entypo-info-circled"></span> <b>Você Precisa preencher no mínimo o nome e sobrenome do passageiro!</b>.');
}
return false;
}
}
});
e.preventDefault();
});