I'm using JQuery Autocomplete. It works fine. However, if a person enters a customer name where there is no result I want to display a Bootstrap error message. That also works BUT only the first time. If you make a second entry into the search field which is also wrong, then the if ((data.length == 0) || $.isEmptyObject(data) || (data == null) ) renders TRUE but regardless I do not get my error message. I even try to empty the data object after the alert. I have also placed console.log() messages throughout the if statement to ensure that I am not making an error in terms of process flow. I can see that the if() statement is being triggered. But somehow the alert only works on the first pass. So what have I done wrong ? TKS!
$('#customer').autocomplete({
minLength:3,
source: function(request, response,term) {
var param = request.term;
$.ajax({
url: "quotes/customer_search/"+param,
dataType: "json",
type:"GET",
success: function (data) { console.log('l 132',data);
if ((data.length == 0) || $.isEmptyObject(data) || (data == null) ) console.log('l 133', data)
{ $("#search_customer").addClass("alert alert-warning fade in").append('No Such Person Found',"<a href='#' class=close data-dismiss='alert' aria-label='close' title='close'>×</a>" ); /* .hide(5000); */
delete data ; console.log('l 135', data);
}
response($.map(data, function(item, index) { console.log('l 139', data);
return item.id+" "+item.firstname1+" "+item.lastname1+" "+item.telephone1;
}
));//END Success
},
});//END AJAX
},
It's clear from this Fiddle that "something" is happening to the search_customer element on close of the alert. Notice how the "test" message disappears after the alert is closed.
JQuery:
HTML:
So, inspect that HTML after closing the alert and you'll find the div is gone:
This is because
data-dismissremoves the element. Goodbye div!Try using
data-hideinstead, as described here:Twitter Bootstrap alert message close and open again
P.S. you're also missing quotes around
class=close.Update:
Even with the above approach, there is still an issue with binding the click event to the dynamically added element. You might consider having your alert loaded in the DOM, but hidden initially. You then can toggle it. Here is a fiddle showing this approach.