开发者

source only allowed values in JQuery UI autocomplete plugin

Is is possible to restrict the user input to only the source开发者_JAVA百科 values with JQuery autocomplete plugin?

For example, if the source array contains "Bold","Normal","Default","100","200", the user is allowed to only type those values.


I see you already have a solution. Here's a similar way to do this, since I already put some time in on it.

http://jsfiddle.net/pxfunc/j3AN7/

var validOptions = ["Bold", "Normal", "Default", "100", "200"]
previousValue = "";

$('#ac').autocomplete({
    autoFocus: true,
    source: validOptions
}).keyup(function() {
    var isValid = false;
    for (i in validOptions) {
        if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
            isValid = true;
        }
    }
    if (!isValid) {
        this.value = previousValue
    } else {
        previousValue = this.value;
    }
});


I have a simple alternative. Check this out:

http://jsfiddle.net/uwR3Z/2/

Basically an onChange event on the textbox to clear out the value works the same.

Here is the js:

var validOptions = ["Bold", "Normal", "Default", "100", "200"];

$('#auto-complete-input').autocomplete({
    autoFocus: true,
    source: validOptions
});

function clearAutoCompleteInput() {
    $("#auto-complete-input").val('');
}

And html:

<label for="auto-complete-input">Select one: </label>
<input id="auto-complete-input" type="text" onChange="clearAutoCompleteInput()" />


I agree with the comment made by Rephael, as you want to limit the possible values to the one in autocomplete, a safer choice would be to have a select dropdown. As a final user can be frustrating to enter data in a textbox and not being able to write what I want. The choice of a select dropdown is "socially" accepted to be limited.


I figured out a way.

Add the following option to the plugin. This works for when the source is an array.

change: function (event, ui) {
        if (!ui.item) {
            var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                                    valid = false;

        $.each(YOUR_SOURCE_ARRAY_NAME, function (index, value) {
               if (value.match(matcher)) {
               this.selected = valid = true;
                   return false;
               }
            });
            if (!valid) {
                // remove invalid value, as it didn't match anything
                $(this).val("");
            return false;
            }
        }
}


This is an old question but I what I do is

  1. set a flag to false when entering the field (onfocus)
  2. Set the flag to true in the autocomplete select event
  3. Test that flag in the field onblur event.

If it is true the input is good, otherwise it is bad.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜