开发者

How to map json values to jQuery UI's expected "value" and "label"?

I'm trying to get jQuery autocomplete working. The problem is that my json array is composed of the properties "name" and "id". jQuery expects "value" and "label". I want to map "name" to "label" and "id" to "value".

Here is a working example, in which I'm using the expected jQuery property names:

    $(function() {
        var projects = [
            {value: "aaron-112", label: "Aaron"},
            {value: "andy-123", label: "Andy" },
            {value: "greg-122", label: "Greg" }];

        $( "#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 );
                $( "#project-id" ).val( ui.item.value );
                return false;
            }
        })
        .data( "autocomplete" )._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>" + item.label + "</a>" )
                .appendTo( ul );
        };
    });
    </script>

<div class="demo">
    <input id="project"/>
    <input type="hidden" id=开发者_如何学编程"project-id"/>
    </div>

But my json looks like this:

   [{id: "aaron-112", name: "Aaron"},
    {id: "andy-123", name: "Andy" },
    {id: "greg-122", name: "Greg" }];


Could you modify the data before using it with the plugin?

For example:

var newProjects = [];
$.each(projects, function() { 
  newProjects.push( { value: this.id, label: this.name } );
});

And then use newProjects with the plugin?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜