Autocomplete disallow free text entry?

前端 未结 7 1287
忘了有多久
忘了有多久 2020-12-02 15:27

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 pre

7条回答
  •  旧时难觅i
    2020-12-02 16:08

    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                                
            });
    

提交回复
热议问题