在一个页面上有多个jQuery自动完成组合框的实例

时间:2012-03-12 16:07:15

标签: jquery autocomplete combobox

我想在一个html页面上有多个JQuery自动完成组合框。 (怎么样)这是可能的吗?

我发现组合框的id很重要。在下面的示例中,使用JQuery显示的唯一组合框是第一个。 我不想复制(太多)JQuery脚本代码(我将此代码放在.js文件中并在.php文件中生成组合框)

我有这个(这只是http://jqueryui.com/demos/autocomplete/#combobox的演示示例中的代码)

<select id="combobox">
    <option value="">Select one...</option>
    <option value="ActionScript">ActionScript</option>
    <option value="AppleScript">AppleScript</option>
    <option value="Asp">Asp</option>
    <option value="BASIC">BASIC</option>
    <option value="C">C</option>
    <option value="C++">C++</option>
    <option value="Clojure">Clojure</option>
    <option value="COBOL">COBOL</option>
    <option value="ColdFusion">ColdFusion</option>
    <option value="Erlang">Erlang</option>
    <option value="Fortran">Fortran</option>
    <option value="Groovy">Groovy</option>
    <option value="Haskell">Haskell</option>
    <option value="Java">Java</option>
    <option value="JavaScript">JavaScript</option>
    <option value="Lisp">Lisp</option>
    <option value="Perl">Perl</option>
    <option value="PHP">PHP</option>
    <option value="Python">Python</option>
    <option value="Ruby">Ruby</option>
    <option value="Scala">Scala</option>
    <option value="Scheme">Scheme</option>
</select>
<select id="combobox2">
    <option value="">Select one...</option>
    <option value="ActionScript">ActionScript</option>
    <option value="AppleScript">AppleScript</option>
    <option value="Asp">Asp</option>
    <option value="BASIC">BASIC</option>
    <option value="C">C</option>
    <option value="C++">C++</option>
    <option value="Clojure">Clojure</option>
    <option value="COBOL">COBOL</option>
    <option value="ColdFusion">ColdFusion</option>
    <option value="Erlang">Erlang</option>
    <option value="Fortran">Fortran</option>
    <option value="Groovy">Groovy</option>
    <option value="Haskell">Haskell</option>
    <option value="Java">Java</option>
    <option value="JavaScript">JavaScript</option>
    <option value="Lisp">Lisp</option>
    <option value="Perl">Perl</option>
    <option value="PHP">PHP</option>
    <option value="Python">Python</option>
    <option value="Ruby">Ruby</option>
    <option value="Scala">Scala</option>
    <option value="Scheme">Scheme</option>
</select>

(function( $ ) {
    $.widget( "ui.combobox", {
        _create: function() {
            var self = this,
                select = this.element.hide(),
                selected = select.children( ":selected" ),
                value = selected.val() ? selected.text() : "";
            var input = this.input = $( "<input>" )
                .insertAfter( select )
                .val( value )
                .autocomplete({
                    delay: 0,
                    minLength: 0,
                    source: function( request, response ) {
                        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                        response( 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"
                                        ), "<strong>$1</strong>" ),
                                    value: text,
                                    option: this
                                };
                        }) );
                    },
                    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 ) {
                                // remove invalid value, as it didn't match anything
                                $( this ).val( "" );
                                select.val( "" );
                                input.data( "autocomplete" ).term = "";
                                return false;
                            }
                        }
                    }
                })
                .addClass( "ui-widget ui-widget-content ui-corner-left" );

            input.data( "autocomplete" )._renderItem = function( ul, item ) {
                return $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( "<a>" + item.label + "</a>" )
                    .appendTo( ul );
            };              

            this.button = $( "<button type='button' class='ui-button ui-widget ui-state-default ui-button-icon-only ui-corner-right ui-button-icon ui-state-hover'><span class='ui-button-icon-primary ui-icon ui-icon-triangle-1-s'></span><span class='ui-button-text'>&nbsp;</span></button>" )
                .attr( "tabIndex", -1 )
                .attr( "title", "Show All Items" )
                .attr( "role", "button" )
                .attr( "aria-disabled", "false" )
                .insertAfter( input )
                .button({
                    icons: {
                        primary: "ui-icon-triangle-1-s"
                    },
                    text: false
                })
                .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();
                });
        },

        destroy: function() {
            this.input.remove();
            this.button.remove();
            this.element.show();
            $.Widget.prototype.destroy.call( this );
        }
    });
})( jQuery );

$(function() {
    $( "#combobox" ).combobox();
    $( "#toggle" ).click(function() {
        $( "#combobox" ).toggle();
    });
});

谢谢!

2 个答案:

答案 0 :(得分:6)

假设您只需要选择目标元素,您只需按类或多个ID进行选择:

$('.combobox').combobox(); // would need to add this shared class to markup

// OR
$('#combobox, #combobox2').combobox(); // should work with existing markup

我更喜欢使用类,因此您不必总是在增长时手动添加更多ID。

请注意,它们包含的切换按钮就像展示底层“真实”组合框的演示一样。我认为你不需要绑定一个切换。

[评论中发现的小提琴:]

http://jsfiddle.net/6wMz9/(使用ID)

http://jsfiddle.net/6wMz9/1/(4个组合框,使用课程)

答案 1 :(得分:4)

user1264532

我想做同样的事情,我有多个组合框实例,但ID就是问题,所以我所做的就是在autocomplete.combobox示例创建的范围中添加相同的ID。唯一的变化是在构造函数中:

        _create: function () {
        console.log(this);
            this.wrapper = $("<span>")
                .addClass("custom-combobox")
                .insertAfter(this.element)
                .attr('id', this.element[0].id+'_combobox');
            this.element.hide();
            this._createAutocomplete();
            this._createShowAllButton();
        },

就这样称呼它

    $("#combobox1").combobox();
    $("#combobox2").combobox();

我这样做因为我需要在每个组合框上捕获更改事件,而在其他答案中我无法实现这一点。希望这会有所帮助。

这是一个jsFiddle example欢呼!