user2269352
user2269352

Reputation: 187

Knockout jQueryUI Autocomplete how to use input value if nothing selected from autocomplete list

I am using the custom binding provided in How to create an auto-complete combobox?

I want to allow the user to either select a value from the list of suggestions or enter a value that is not in the list of suggestions. How can I get the value of the input into my observable field?

For example, if the user types 'smi' the autocomplete list will show Smith and other surnames beginning with 'smi', however, if they do not select an option from the list, I just want to set the value of my observable field to be 'smi'. At present, the only way the observable propety is set is when the user selects an item from the list of suggestions.

I have the following code (HTML):

<input type="text" data-bind="
                            value: surname,
                            jqAuto: { autoFocus: true },
                            jqAutoSource: surnames,
                            jqAutoQuery: surnameAutocomplete,
                            jqAutoValue: surname" 
            />

JavaScript view model (simplified):

var vm = {
    surnames: ko.observableArray(),
     surname: ko.observable(),
     surnameAutocomplete: function (searchTerm, result) {
        repository.surnameAutocomplete(searchTerm, result);
    };

Solution:

I amended the custom binding handler in two places:

I also found that the first item in the autocomplete list was being automatically selected, but then noticed by setting autofocus: false solved my issue, e.g.,

<input type="text" data-bind="                                
                            jqAuto: { autoFocus: false }, /* This fixes the auto select issue */
                            jqAutoSource: surnames,
                            jqAutoQuery: surnameAutocomplete,
                            jqAutoValue: surname,
                            jqAutoForceSelection: false"
            />

Upvotes: 2

Views: 2226

Answers (1)

Rune Vejen Petersen
Rune Vejen Petersen

Reputation: 3239

If you look closely at the binding handler you're using, you will notice this section:

//on a change, make sure that it is a valid value or clear out the model value
    options.change = function(event, ui) {
        var currentValue = $(element).val();
        var matchingItem =  ko.utils.arrayFirst(unwrap(source), function(item) {
           return unwrap(item[inputValueProp]) === currentValue;  
        });

        if (!matchingItem) {
           writeValueToModel(null);
        }  

What this section of the binding handler essentially does is check if the text the user entered into the text field matches something in the autocomplete dropdown, and if it doesn't, it clears the model value (which it sounds like what you want to change).

You can either try deleting this section or extend it to suit your purposes.

Upvotes: 1

Related Questions