How to implement “mustMatch” and “selectFirst” in jQuery UI Autocomplete?

前端 未结 13 868
一向
一向 2020-11-27 11:47

I recently migrated a few of my Autocomplete plugins from the one produced by bassistance to the jQuery UI autocomplete.

How can the \"mustMatch\" and \"selectFirst\

相关标签:
13条回答
  • 2020-11-27 12:35

    Here a simple definitive solution for "mustMatch" requirement:

    <script type="text/javascript">
        $(function() {
            $("#my_input_id").autocomplete({
                source: '/get_my_data/',
                minChars: 3,
                select: function(event, ui) {
                    // custom code
                    $(this).data("pre-ui-autocomplete-value", $(this).val());
                }
            }).on("focus", function () {
                $(this).data("pre-ui-autocomplete-value", $(this).val());
            }).on("blur", function () {
                $(this).val($(this).data("pre-ui-autocomplete-value"));
            });
        });
    </script>
    
    0 讨论(0)
  • 2020-11-27 12:38

    I'm doing it a little differently, caching the results and clearing the text field if the number of results for a certain term is zero:

    <script type='text/javascript'>
    function init_autocomplete( args )
    {
         var resultCache = {};
         var currentRequestTerm = null;
    
         var closeCallback = function()
         {
             // Clear text field if current request has no results
             if( resultCache[currentRequestTerm].length == 0 )
                 $(args.selector).val('');
         };
    
         var sourceCallback = function( request, responseCallback )
         {
             // Save request term
             currentRequestTerm = request.term;
    
             // Check for cache hit
             // ...
             // If no cache hit, fetch remote data
             $.post(
                 dataSourceUrl,
                 { ...  }, // post data
                 function( response )
                 {
                     // Store cache
                     resultCache[request.term] = response;
    
                     responseCallback( response );
                 }
         };
    
         $(args.selector).autocomplete({
             close:  closeCallback,
             source: sourceCallback
         });
    }
    </script>
    
    0 讨论(0)
  • 2020-11-27 12:41

    Late reply but might help someone!

    Considering the two events in autocomplete widget

    1) change - triggered when field is blurred and value is changed.

    2) response - triggered when the search completes and the menu is shown.

    Modify the change and response events as follows:

    change : function(event,ui)
    {  
    if(!ui.item){
    $("selector").val("");
    }
    },
    
    response : function(event,ui){
    if(ui.content.length==0){
      $("selector").val("");
    }
    }
    

    Hope this helps!

    0 讨论(0)
  • 2020-11-27 12:43

    The solution I've used to implement 'mustMatch':

    <script type="text/javascript">
    ...
    
    $('#recipient_name').autocomplete({
        source: friends,
        change: function (event, ui) {
            if ($('#message_recipient_id').attr('rel') != $(this).val()) {
                $(this).val('');
                $('#message_recipient_id').val('');
                $('#message_recipient_id').attr('rel', '');
            }
        },
        select: function(event, ui) {
            $('#message_recipient_id').val(ui.item.user_id);
            $('#message_recipient_id').attr('rel', ui.item.label);
        }
    }); 
    
    ...
    </script>
    
    0 讨论(0)
  • 2020-11-27 12:45

    I found this question to be useful.

    I thought I'd post up the code I'm now using (adapted from Esteban Feldman's answer).

    I've added my own mustMatch option, and a CSS class to highlight the issue before resetting the textbox value.

           change: function (event, ui) {
              if (options.mustMatch) {
                var found = $('.ui-autocomplete li').text().search($(this).val());
    
                if (found < 0) {
                  $(this).addClass('ui-autocomplete-nomatch').val('');
                  $(this).delay(1500).removeClass('ui-autocomplete-nomatch', 500);
                }
              }
            }
    

    CSS

    .ui-autocomplete-nomatch { background: white url('../Images/AutocompleteError.gif') right center no-repeat; }
    
    0 讨论(0)
  • 2020-11-27 12:46

    I think I solved both features...

    To make things easier, I used a common custom selector:

    $.expr[':'].textEquals = function (a, i, m) {
        return $(a).text().match("^" + m[3] + "$");
    };
    

    The rest of the code:

    $(function () {
        $("#tags").autocomplete({
            source: '/get_my_data/',
            change: function (event, ui) {
                //if the value of the textbox does not match a suggestion, clear its value
                if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
                    $(this).val('');
                }
            }
        }).live('keydown', function (e) {
            var keyCode = e.keyCode || e.which;
            //if TAB or RETURN is pressed and the text in the textbox does not match a suggestion, set the value of the textbox to the text of the first suggestion
            if((keyCode == 9 || keyCode == 13) && ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0)) {
                $(this).val($(".ui-autocomplete li:visible:first").text());
            }
        });
    });
    

    If any of your autocomplete suggestions contain any 'special' characters used by regexp, you must escape those characters within m[3] in the custom selector:

    function escape_regexp(text) {
      return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    }
    

    and change the custom selector:

    $.expr[':'].textEquals = function (a, i, m) {
      return $(a).text().match("^" + escape_regexp(m[3]) + "$");
    };
    
    0 讨论(0)
提交回复
热议问题