开发者

jQuery UI autocomplete custom html

I'm using the jQuery UI autoc开发者_开发技巧omplete for a custom html drop down list. To render the drop down list, I have to use a hack. This hack gets called as the javascript gets loaded (which I do not want). I have this code in another file, and not always will I need to use the autocomplete method.

Here is my code:

View:

<input id="project"/>
<div id="tmp" style="display: none;"></div>

<script type="text/html" id="templateHolder">    
    <a>
    {$T.value}
    <br />
    {$T.label}
    </a>
</script>

Script.js

$(function () {    

    var projects = [
        {
            value: "jquery",
            label: "jQuery"
        },
        {
            value: "jquery-ui",
            label: "jQuery UI"
        }
        ];

  $("#project").autocomplete({
    minLength: 0,
    source: projects,
    focus: function (event, ui) {
        $("#project").val(ui.item.label);
        return false;
    },
    select: function (event, ui) {
        $("#project").val(ui.item.label);

        return false;
    }
  }).data("autocomplete")._renderItem = function (ul, item) {
        var tmp = $("<div>").setTemplate($("#templateHolder").html());
        tmp.processTemplate(item);
        $("<li></li>").data("item.autocomplete", item)
                      .append($(tmp).html())
                      .appendTo(ul);
        return;
    };
});

The .data('autocomplete') section is the hack. Is there a way to go around this so when there is no autocomplete (no #project is found), it does not throw a javascript error?

Also: When 2 autocompletes are on the page, only the first one works.


Simply apply the autocompleter if #project exists, which can be determined by checking the length property of the jQuery object formed by that selector:

if($("#project").length) {
    $("#project").autocomplete({...
}

If you are going to have more than one autocompleter, then you will need another selector since duplicate IDs are causing the problem of only the first one working. E.g.:

if($(".project").length) {
    $(".project").autocomplete({...
}

A single page should not contain any duplicate IDs as per the specification.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜