我使用jqueryui自动完成插件与以下代码

$(this).autocomplete({
                source: function(request, response) {
                    $.ajax({ url: 'clinic/auto',
                    data: { 'term': this.term,'name': this.element.attr('complete')},
                    dataType: "json",
                    type: "POST",
                    success: function(data){
                        response(data);
                    }
                });
            },
            minLength: 2
        });

这将显示所有结果列表的下拉列表。

我的问题是如何让您自动完成工作并突出显示添加的部分以便于使用?

我需要编写代码吗?还是已经有一个选择?
如果我手动做,该怎么办?
图片示例:

到目前为止的解决方案:

我发现这个link and this对编辑样式非常有用(monkey-patching jquery-autocomplete),但仍然不是我想要的。

最佳答案

不幸的是,没有现成的选择。幸运的是,有一种非常简单的方法可以使用JQuery Autocomplete提供的事件来实现。看看这个JSFiddle:http://jsfiddle.net/RyTuV/133/

您会注意到,要添加的相关代码使用了JQuery Autocomplete Open event:



使用此事件,您可以将列表中第一项的文本添加到已经输入到输入字段中的文本,然后从输入文本之后到添加文本的末尾突出显示:

$(this).autocomplete({
    source: function(request, response) {
                $.ajax({ url: 'clinic/auto',
                data: { 'term': this.term,'name': this.element.attr('complete')},
                dataType: "json",
                type: "POST",
                success: function(data){
                    response(data);
                }
            });
    },
    minLength: 2,
    open: function( event, ui ) {
        var firstElement = $(this).data("autocomplete").menu.element[0].children[0]
           , inpt = $('#autocomplete')
           , original = inpt.val()
           , firstElementText = $(firstElement).text();

        /*
           here we want to make sure that we're not matching something that doesn't start
           with what was typed in
        */
        if(firstElementText.toLowerCase().indexOf(original.toLowerCase()) === 0){
            inpt.val(firstElementText);//change the input to the first match

            inpt[0].selectionStart = original.length; //highlight from end of input
            inpt[0].selectionEnd = firstElementText.length;//highlight to the end
        }
    }
});

使用此模板作为模板,您可以循环浏览菜单中的项目以查找以输入文本开头的第一个匹配项,然后使用其进行填写和突出显示,而不是仅使用第一个项目。

关于带有第一个值的jquery自动完成自动填充字段,并突出显示添加的部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14062765/

10-11 14:41
查看更多