Vince Vince - 2 years ago 52
Javascript Question

How to eliminate an object to satisfy my if statement

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) )
but regardless I do not get my error message. I even try to empty the data object after the alert. I have also placed
messages throughout the if statement to ensure that I am not making an error in terms of process flow. I can see that the
statement is being triggered. But somehow the alert only works on the first pass. So what have I done wrong ? TKS!

source: function(request, response,term) {

var param = request.term;
url: "quotes/customer_search/"+param,
dataType: "json",
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.firstname1+" "+item.lastname1+" "+item.telephone1;

));//END Success

Answer Source

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.


$('#test').click(function() {
  $("#search_customer").addClass("alert alert-warning").append('No Such Person Found', "<a href='#' class=close data-dismiss='alert' aria-label='close' title='close'>×</a>");



<div id="search_customer">
<input id="test" type="button" value="Click Me!">

So, inspect that HTML after closing the alert and you'll find the div is gone: hey where's my div

This is because data-dismiss removes the element. Goodbye div!

Try using data-hide instead, as described here:

Twitter Bootstrap alert message close and open again

P.S. you're also missing quotes around class=close.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download