Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

jquery - Autocomplete disallow free text entry?

Is it possible to disallow free text entry in the JQuery UI autocomplete widget?

eg I only want the user to be allowed to select from the list of items that are presented in the autocomplete list, and dont want them to be able to write some random text.

I didn't see anything in the demos/docs describing how to do this.

http://jqueryui.com/demos/autocomplete/

I'm using autocomplete like this

$('#selector').autocomplete({
    source: url,
    minlength: 2,
    select: function (event, ui) {
        // etc
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the API documentation, the change event's ui property is null if the entry was not chosen from the list, so you can disallow free text as simply as this:

$('#selector').autocomplete({
    source: url,
    minlength: 2,
    change: function(event, ui) {
        if (ui.item == null) {
          event.currentTarget.value = ''; 
          event.currentTarget.focus();
        }
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...