Lock
Lock

Reputation: 5522

JQuery- clear field on lost focus unless the field was populated from dropdown

I have a textbox where the user puts in some text, and a dropdown appears. When the user selects something from the dropdown list, the text from the dropdown replaces the text that they typed.

Now, I want this textbox to clear itself if they didn't select anything from the dropdown.

So basically, the only text that can appear in the textbox is something that was ultimately selected from the dropdown. How would I achieve this?

I've tried:

  jQuery("#" + field).focusout(function() {
    jQuery("#" + field).val("");

  });

But this still clears even if they selected from the dropdown. What logic would I implement to do this? Could I set a variable or something that is set to true when they select from a list. I would then check this on the focusout function?

Quite new to JQuery!

Upvotes: 3

Views: 3778

Answers (2)

billyonecan
billyonecan

Reputation: 20270

Use the autocomplete change event, check for the existence of ui (the item selected from the menu, if any. Otherwise the property is null), if it doesn't exist, then you know the user didn't select an autocomplete option, and you can empty the value:

change: function (ev, ui) {
    if (!ui.item) {
        $(this).val('');
    }
}

Here's a simple demo fiddle

Upvotes: 8

g7876413
g7876413

Reputation: 279

Possibly something like this:

jQuery("#" + field).focusout(function() {
    var enteredValue = $("#" + field).val();
    var listOfAvailableOptions = //put method call here
    if($inArray(enteredValue, listOfAvailableOptions)) //possibly use IndexOf() here and check if = -1
{
    jQuery("#" + field).val("");

}
});

The neater way would be to populate the values of a combo box from the AJAX call though

Upvotes: -1

Related Questions