46

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
    }
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
JK.
  • 21,477
  • 35
  • 135
  • 214

7 Answers7

92

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();
        }
    }
});
Andreas
  • 5,393
  • 9
  • 44
  • 53
Neils
  • 1,513
  • 1
  • 12
  • 7
10

If you want the user to just get the item from the list then use autocomplete combobox.

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

HTH

Chad Birch
  • 73,098
  • 23
  • 151
  • 149
Raja
  • 3,608
  • 3
  • 28
  • 39
  • 4
    You can still type into that, that's exactly what he said he didn't want. – Chad Birch May 25 '10 at 23:00
  • 1
    No I don't think he wants that. I think he wants to get it from the item from the list i.e. if the user starts to type "Ja" then if it lists "Java" and "Javascript" then he wants the user to select from one of them and not type "Jab" and submit. – Raja May 25 '10 at 23:03
  • 1
    No I said autocomplete, which implies typing is allowed. But the typing must be restricted to only items in the autocomplete list. The combobox example does exactly that. – JK. May 25 '10 at 23:03
  • Combobox functionally is perfect, but the UI is bad - it looks very different from standard the < select >, so I can't use it. I will look at the example in more detail to see if the drop down button can be left out. – JK. May 25 '10 at 23:05
  • 1
    I'm the one that misunderstood what he wanted then. Made an irrelevant edit to this answer so I could take back my downvote. – Chad Birch May 25 '10 at 23:09
3

One way would be to use additional validation on form submit (if you are using a form) to highlight an error if the text isn't one of the valid option.

Another way would be to attach to the auto complete's change event which will get fired even if an options isn't selected. You can then do validation to ensure the user input is in your list or display an error if it is not.

Aaron Janes
  • 304
  • 3
  • 11
  • I went with the .change() event, it was easier and quicker than trying to change the combobox solution to fit. – JK. May 26 '10 at 02:25
  • @Neils pointed out below another answer and that worked like a charm change: function(event,ui) { if (ui.item==null) { $("#your_input_box").val(''); $("#your_input_box").focus(); } } – Sandeep Aug 05 '14 at 23:33
0

I used the combobox module which gives you a "down arrow" button. Then to the input tag, just add the following to the input tag right around line 41 (depending on your version of the combobox http://jqueryui.com/demos/autocomplete/#combobox )

input.attr("readonly", "readonly");

Then add code so that if the user clicks the input box, it'll show the drop list.

For my purposes, I added a readonly flag that I can pass in to the module so if I need it readonly, I can turn it on/off as well.

Mike
  • 217
  • 4
  • 16
0

Old question, but here:

    var defaultVal = '';
    $('#selector').autocomplete({
        source: url,
        minlength: 2,
        focus: function(event, ui) {
            if (ui != null) {
                defaultVal = ui.item.label;
            }
        },
        close: function(event, ui) {
            $('#searchBox').val(defaultVal);
        }
    });
VGR
  • 40,506
  • 4
  • 48
  • 63
Joe
  • 7,922
  • 18
  • 54
  • 83
0

If you would like to restrict the user to picking a recommendation from the autocomplete list, try defining the close function like this. The close function is called when the results drop down closes, if the user selected from the list, then event.currentTarget is defined, if not, then the results drop down closed without the user selecting an option. If they do not select an option, then I reset the input to blank.

/**
 * The jQuery UI plugin autocomplete
 */
$.widget( "ui.autocomplete", $.ui.autocomplete, {
   options: {
      close: function( event, ui ) {
         if (typeof event.currentTarget == 'undefined') {
            $(this).val("");
         }
      }
   }
 });
user7793758
  • 79
  • 1
  • 4
  • While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – nircraft Oct 24 '19 at 14:33
  • In this particular example, i extend the autocomplete ui widget to behave this way so I don't have to fix every place it occurs in my application. If you only have a few, then just define the close function and don't bother extending the widget – user7793758 Oct 24 '19 at 14:45
-1

The combobox option works well if you are using a set list, however if you have a dynamic generated list via a json get, then you can only capture the data on change.

Full example with additional parameters below.

        $("#town").autocomplete(
        {       
            select: function( event, ui ) {
                $( "#town" ).val( ui.item.value );
                return false;
            },        
            focus: function( event, ui ) {
                    $( "#town" ).val( ui.item.label );
                    return false;
                },           
            change: function(event, ui) {
                if (!ui.item) {
                    $("#town").val("");
                }
            },
            source: function(request, response) {
                $.ajax({
                    url: 'urltoscript.php',
                    dataType: "json",
                    data: {
                        term : request.term,
                        country : $("#abox").val()    // extra parameters
                    },                        
                    success: function(data) {
                        response($.map(data,function (item)
                        {                                
                            return {
                                id: item.id,
                                value: item.name
                            };
                        }));
                    }
                });
            },
            minLength: 3
            , highlightItem: true                                
        });
PodTech.io
  • 4,874
  • 41
  • 24