开发者

jQuery UI Autocomplete multiple term search

I am attempting to use the jQuery UI Autocomplete functionality. After a good bit of searching, prior to simply writing my own, perhaps there is solution already available.

I previously used the jQuery plugin http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ but for various reasons want to migrate to the one integrated in the UI.

Two items currently have me challenged.

Selected terms highlight and multiple terms search/selection and how to achieve those.

Here is a fiddle page: http://jsfiddle.net/vapc2/ to show the example. Type in "ants" and it will hightlight the ants. But if I type "ants jill hill" it should select and highlight all the entries with "ant", all with "jill" and all with "hill" in them, not nothing as it does now. Basically, if a term appears anywhere, in any answer I want to return that value and highlight that term, even if it is not an exact match, just so it is contained in the answer somewhere. So if I type "ant bug" I want to return all the entries with either of those two words.

Say I have the following example JSON object:

var sampleAnswers = [
    {
    "id": "00450",
    "label": "Ants, Ants on a hill near Jill",
    "Category": "Ants",
    "value": "hill ant"},
{
    "id": "00450",
    "label": "Ants, Ant not on a hill",
    "Category": "Ants",
    "value": "regular ant"},
{
    "id": "00452",
    "label": "Some ants on a hill",
    "Category": "Ants",
    "value": "hill ants"},
{
    "id": "00454",
    "label": "Red ants on a hill near Jill",
    "Category": "Ants",
    "value": "hill ant red"},
{
    "id": "00470",
    "label": "Bugs on a rug",
    "Category": "bugs",
    "value": "rug bug"},
{
    "id": "00472",
    "label": "rug bugs under the rug",
    "Category": "bugs",
    "value": "rug bug"},
{
    "id": "69000",
    "label": "bed bugs",
    "Category": "bed",
    "value": "bed bugs"},
{
    "id": "69005",
    "label": "Large complicated bed bugs",
    "Category": "bugs",
    "value": "bed bug"},
{
    "id": "69020",
    "label": "red bed bugs",
    "Category": "bugs",
    "value": "red bugs"}
];
function replaceWords(wordsy, text) {
    //var re = '(' + words.join('|') + ')(?![^<]*(?:<\/script|>))',
    var re = '(' + wordsy + ')(?![^<]*(?:<\/script|>))',
        regExp = new RegExp(re, 'ig'),
        sTag = "<span class='autoCompleteWord'>",
        eTag = "</span>";
    return text.replace(regExp, sTag + '$&' + eTag);
};
$("#tags").autocomplete({
    minLength: 1,
    source开发者_运维技巧: sampleAnswers,
    delay: 1000,
    focus: function(event, ui) {
        $("#cpt").val(ui.item.label);
        return false;
    },
    open: function(event, ui) {
        var myValue = $(this).val(); //get typed
        $("ul.ui-autocomplete li a").each(function() {
            var autoCompleteRow = $(this);
            var htmlString = autoCompleteRow.html();
            var words = myValue.split(" ");
            $('#mesText2').val(myValue + ":" + words.length);
            var i = words.length;
            while (i--) {
                htmlString = replaceWords(words[i], htmlString);
            };
            autoCompleteRow.html(htmlString);
        });
    },
    select: function(event, ui) {
        var hasValue = (ui.item.value != undefined && ui.item.value != "" && ui.item.value != null);
        $("#bugid").val(ui.item.id);
        $("#bugcategory").val(ui.item.Category);
        $("#bug").val(hasValue ? ui.item.value : ui.item.label);
        $("#bugLabel").val(ui.item.label);

        return false;
    }
}).data("autocomplete")._renderItem = function(ul, item) {
    return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.id + " <span class='autoCompCat'>" + item.Category + "</span> (Category)<br/>" + item.label + " <br/><span class='autoCompCpt'>" + item.value + "</span>" + "</a>").appendTo(ul);
};

markup:

<p><label class='mesFieldLabel'>
    ya typed:</label><input id='mesText2' type='text' class='mesText' /></p><div class="ui-widget cptarea">
<label class='mesFieldLabel' for="tags">Tags:</label>
<input id="tags" /><span class='testCSS'>type 'ant' for example</span>
</div>
<div class='bugarea'>
    <div>
        <label class='mesFieldLabel'>
            Code:</label><input id='bugid' maxlength="100" />
    </div>
    <div>
        <label class='mesFieldLabel'>
            Category:</label><input id='bugcategory' maxlength="100" />
    </div>
    <div>
        <label class='mesFieldLabel'>
            Bug:</label><input id='bug' maxlength="100" />
    </div><div>
    <label class='mesFieldLabel'>
        Bug Label:</label><input id='bugLabel' maxlength="100" />
    </div>
</div>

jQuery UI latest version, jQuery 1.6 is preference.

EDIT: I attempted to use the following "source":

    source: function(request, response) {
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
        response($.each(sampleAnswers, function() {
            var text = $(this).label;
            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
                };
        }));
    },

but this returns results NOT including my list of terms I type (like "red bug" returns items 00450, 00450, 00452) that I do NOT want displayed. See this fiddle for that update: http://jsfiddle.net/vapc2/1/


Ok I solved the problem of it returning all results and not filtering

http://jsfiddle.net/vapc2/4/

Here is the code changes I made -- things to note:

  • I changed $(this) to this.
  • I added in an results array and only added to that when the test passed (as per my original comment.)
  • Your regex does not work, but I think that is outside the scope of this question.

    source: function(request, response) {
    
      var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
    
      var resultset = [];
    
      $.each(sampleAnswers, function() {
    
        var t = this.label;
    
        if (this.value && (!request.term || matcher.test(t)))
        {
           resultset.push( {
    
           label: t.replace(
                     new RegExp(
                             "(?![^&;]+;)(?!<[^<>]*)(" +
                             $.ui.autocomplete.escapeRegex(request.term) +
                             ")(?![^<>]*>)(?![^&;]+;)", "gi"
                           ), "<strong>$1</strong>"),
           value: t,
           option: this
         });
       }  
       return;
     });
    
     response(resultset);
    
    },
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜