user2067567
user2067567

Reputation: 3803

Clear textbox when no matching value found in AutoComplete

I have implemented AutoComplete textbox which is working as Expected.

Currently if "No Match" found in the suggest am showing No results as a suggestion but when they click the value is applied to tex box

var error = ["No match"];
if (results.length == 0) {
    responseFn(error);
}
else {
    responseFn(results);
}

Where results is the list of matching items to be displayed in autosuggest.if results is empty it ll suggest saying "No Match" But i don want user to select that so i tried the below code in if (results.length == 0) {

$("#txtNewAttributes").blur(function () {
    $("#" + txtbxId).val("");
})

But it clears the textbox in all scenarios like even if matching items found. How can i implement this ?

If only no match found i need to clear the TextBox.

Upvotes: 2

Views: 3180

Answers (3)

ABHISHEK Bandil
ABHISHEK Bandil

Reputation: 81

I was also facing same problem before.

In the jquery.autocomplete, there are different-different callback function like focus, change.

You can clear textbox if match not found using below callback function.

change: function (e, u) {
            //If the No match found" u.item will return null, clear the TextBox.
            if (u.item == null) {
                //Clear the AutoComplete TextBox.
                $(this).val("");
                return false;
            }
        }

This solution was worked for me.

Upvotes: 3

andri
andri

Reputation: 1021

Your code binds an event handler to the input. Try clearing the input directly, something like this :

$("#" + txtbxId).val("");

Upvotes: 0

Anders Lindén
Anders Lindén

Reputation: 7293

Have a global variable

var has_valid_values = false;

set it to false if results.length == 0 and true otherwise.

In the blur handler, use

if (!has_valid_values)
  $("#" + txtbxId).val("");

Upvotes: 0

Related Questions