1
I’m performing an Ajax call and, with this, returning new entries to a table. So far so good, but I want to perform a .prepend()
adding a "Remove" button to each item in the list.
The problem is that button
is added only in the first li
I tried to run jsFiddle but I’m not getting it. So I tried to post the code below in a simplified way:
The flow is simple:
- Client clicks a button to add a new user;
- A Modal is opened with some fields;
- As soon as Submit is given, I make an Ajax call sending the values;
- A JSON is returned, which contains a result that I will add to a list on the screen;
Problem
- I make a
$().each()
followed byif
to check if my "remove" button already exists on that line; - It only adds the button in 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();
});
No offense, but because you have a
if
emptiness???– Andre Figueiredo