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

前端 未结 13 867
一向
一向 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:20

    I used something as simple as this for mustMatch and it works. I hope it helps someone.

            change: function (event, ui) {
                if (!ui.item) {
                     $(this).val('');
                 }
            }
    
    0 讨论(0)
  • 2020-11-27 12:22

    I think I got the mustMatch working with this code... It needs thorough test though:

    <script type="text/javascript">
        $(function() {
            $("#my_input_id").autocomplete({
                source: '/get_my_data/',
                minChars: 3,
                change: function(event, ui) {
                    // provide must match checking if what is in the input
                    // is in the list of results. HACK!
                    var source = $(this).val();
                    var found = $('.ui-autocomplete li').text().search(source);
                    console.debug('found:' + found);
                    if(found < 0) {
                        $(this).val('');
                    }
                }
            });
        });
    </script>
    
    0 讨论(0)
  • 2020-11-27 12:24

    I discovered one issue. While the suggestion list is active you can submit your form even if the value doesn't match the suggestion. To dissallow this I added:

    $('form').submit(function() {
            if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
                $(this).val('');
                $("span").text("Select a valid city").show();
                return false;
            }
    });
    

    This prevents the form from being submitted and displays a message.

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

    Based on the accepted answer:

    My additional requirements: multiple autocompletes, unobtrusive error validation.

    change: function () {
        var target = $(this),
            widget = target.autocomplete('widget'),
            cond = widget.find('li:textEquals("' + target.val() + '")').length === 0;
    
        target.toggleClass('input-validation-error', cond);
    }
    
    0 讨论(0)
  • 2020-11-27 12:33

    Scott Gonzalez has written a selectFirst extension (as well as several others) for jQueryUI AutoComplete.

    • Scott Gonzalez GitHub
    • selectFirst Demo
    0 讨论(0)
  • 2020-11-27 12:34

    This JQuery-UI official demo has mustMatch, amongst other cool stuff: http://jqueryui.com/demos/autocomplete/#combobox

    I've updated it to add autoFill, and a few other things.

    Javascript:

    
    
    /* stolen from http://jqueryui.com/demos/autocomplete/#combobox
     *
     * and these options added.
     *
     * - autoFill (default: true):  select first value rather than clearing if there's a match
     *
     * - clearButton (default: true): add a "clear" button
     *
     * - adjustWidth (default: true): if true, will set the autocomplete width the same as
     *    the old select.  (requires jQuery 1.4.4 to work on IE8)
     *
     * - uiStyle (default: false): if true, will add classes so that the autocomplete input
     *    takes a jQuery-UI style
     */
    (function( $ ) {
        $.widget( "ui.combobox", {
            options: {
                autoFill: true,
                clearButton: true,
                adjustWidth: true,
                uiStyle: false,
                selected: null,
            },
        _create: function() {
            var self = this,
              select = this.element.hide(),
              selected = select.children( ":selected" ),
              value = selected.val() ? selected.text() : "",
                  found = false;
            var input = this.input = $( "" )
                    .attr('title', '' + select.attr("title") + '')
            .insertAfter( select )
            .val( value )
            .autocomplete({
                delay: 0,
                minLength: 0,
                source: function( request, response ) {
                    var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                            var resp = select.children( "option" ).map(function() {
                        var text = $( this ).text();
                        if ( this.value && ( !request.term || matcher.test(text) ) )
                        return {
                            label: text.replace(
                            new RegExp(
                                "(?![^&;]+;)(?!]*)(" +
                                $.ui.autocomplete.escapeRegex(request.term) +
                                ")(?![^]*>)(?![^&;]+;)", "gi"
                            ), "$1" ),
                            value: text,
                            option: this
                        };
                    });
                            found = resp.length > 0;
                    response( resp );
                },
                select: function( event, ui ) {
                    ui.item.option.selected = true;
                    self._trigger( "selected", event, {
                        item: ui.item.option
                    });
                },
                change: function( event, ui ) {
                    if ( !ui.item ) {
                        var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
                        valid = false;
                        select.children( "option" ).each(function() {
                        if ( $( this ).text().match( matcher ) ) {
                            this.selected = valid = true;
                            return false;
                        }
                        });
                        if ( !valid || input.data("autocomplete").term=="" ) {
                        // set to first suggestion, unless blank or autoFill is turned off
                                    var suggestion;
                                    if(!self.options.autoFill || input.data("autocomplete").term=="") found=false;
                                    if(found) {
                                        suggestion = jQuery(input.data("autocomplete").widget()).find("li:first")[0];
                                        var option = select.find("option[text="+suggestion.innerText+"]").attr('selected', true);
                                        $(this).val(suggestion.innerText);
                            input.data("autocomplete").term = suggestion.innerText;
                                self._trigger( "selected", event, { item: option[0] });
                                    } else {
                                        suggestion={innerText: ''};
                                        select.find("option:selected").removeAttr("selected");
                                        $(this).val('');
                            input.data( "autocomplete" ).term = '';
                                        self._trigger( "selected", event, { item: null });
                                    }
                        return found;
                        }
                    }
                }
            });
    
                if( self.options.adjustWidth ) { input.width(select.width()); }
    
                if( self.options.uiStyle ) {
                    input.addClass( "ui-widget ui-widget-content ui-corner-left" );
                }
    
    
            input.data( "autocomplete" )._renderItem = function( ul, item ) {
                return $( "
  • " ) .data( "item.autocomplete", item ) .append( "" + item.label + "" ) .appendTo( ul ); }; this.button = $( " " ) .attr( "tabIndex", -1 ) .attr( "title", "Show All Items" ) .insertAfter( input ) .button({ icons: { primary: "ui-icon-triangle-1-s" }, text: false }) .removeClass( "ui-corner-all" ) .addClass( "ui-corner-right ui-button-icon" ) .click(function() { // close if already visible if ( input.autocomplete( "widget" ).is( ":visible" ) ) { input.autocomplete( "close" ); return; } // work around a bug (likely same cause as #5265) $( this ).blur(); // pass empty string as value to search for, displaying all results input.autocomplete( "search", "" ); input.focus(); }); if( self.options.clearButton ) { this.clear_button = $( " " ) .attr( "tabIndex", -1 ) .attr( "title", "Clear Entry" ) .insertAfter( input ) .button({ icons: { primary: "ui-icon-close" }, text: false }) .removeClass( "ui-corner-all" ) .click(function(event, ui) { select.find("option:selected").removeAttr("selected"); input.val( "" ); input.data( "autocomplete" ).term = ""; self._trigger( "selected", event, { item: null }); // work around a bug (likely same cause as #5265) $( this ).blur(); }); } }, destroy: function() { this.input.remove(); this.button.remove(); this.element.show(); $.Widget.prototype.destroy.call( this ); } }); })( jQuery );

    CSS (.hjq-combobox is a wrapping span)

    .hjq-combobox .ui-button { margin-left: -1px; }
    .hjq-combobox .ui-button-icon-only .ui-button-text { padding: 0; }
    .hjq-combobox button.ui-button-icon-only { width: 20px; }
    .hjq-combobox .ui-autocomplete-input { margin-right: 0; }
    .hjq-combobox {white-space: nowrap;}
    

    Note: this code is being updated and maintained here: https://github.com/tablatom/hobo/blob/master/hobo_jquery_ui/vendor/assets/javascripts/combobox.js

    0 讨论(0)
提交回复
热议问题