LA_
LA_

Reputation: 20409

How to allow to choose only pre-defined options with jquery ui combobox?

Here is my current jquery ui combobox. It uses remote datasource. Here is the approach to apply the same for standard combobox. But I am not sure how to apply that in my case.

Upvotes: 2

Views: 267

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

Just use the change event to see if ui.item is defined:

/* snip */
change: function (event, ui) {
    if (!ui.item) { 
        this.value = 'Any City';
    }
}

Updated example: http://jsfiddle.net/FL7Nx/

Per your comment below, if you want to dynamically figure out what the default value should return to, you could assign that value to the selected option in the widget's _create method:

_create: function() {
    var self = this,
        select = this.element.hide(),
        selected = select.children(":selected"),
        value = selected.val() ? selected.text() : "",
        defaultValue = value;

Then later on in the change function:

change: function (event, ui) {
    if (!ui.item) { 
        this.value = defaultValue;
    }
}

Updated example: http://jsfiddle.net/jmdx4/

Upvotes: 3

Related Questions