jQuery自动完成,多个项目无法正常工作

时间:2013-12-16 13:30:42

标签: javascript jquery ajax json jquery-autocomplete

我正在研究jQuery自动完成功能,它是<ul>中的两个项目。

我从$ .getJSON函数获取json项,json对象如下:

[{
     "merchant_name": "Myntra",
     "merchant_details": "Flat Rs.225 Cashback"
}, {
     "merchant_name": "Adlabs imagica",
     "merchant_details": "Rs 170 per sale"
}, {
     "merchant_name": "godaam",
     "merchant_details": "Rs 140 per sale"
}, {
     "merchant_name": "Homeshop18",
     "merchant_details": "Upto 8% Cashback"
}]

我的功能如下:

$('#search_bar').keyup(function(e) {
    var searched = $('#search_bar').val()
    $.getJSON('<?php echo base_url();?>get_data', 'title=' + searched, function(result) {
        var elements = [];
        $.each(result, function(i, val) {
            elements.push({
                'merchant_name': val.merchant_name,
                'merchant_details': val.merchant_details
            })
        }) $('#search_bar').autocomplete({
            delay: 0,
            source: elements,
            select: function(event, ui) {
                $("input#search_bar").val(ui.item.merchant_name + " / " + ui.item.merchant_details);
                $("#get").click();
            }.data("autocomplete")._renderItem = function(ul, item) {
                return $("<li></li>").data("item.autocomplete", item).append("<a><strong>" + item.merchant_name + "</strong> / " + item.merchant_details + "</a>").appendTo(ul);
            };
        })
    })
});

我无法前进。

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

我为我的一个项目写了这个,它完美无缺。我不确定为什么在自动完成为您执行此操作时检测到密钥的原因...但此代码段应该为您提供所需的所有功能。

$("#edit_profile .location").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: BASE_URL + "lib/ajax.php",
                type: "GET",
                data: "autocomplete_location=1&term=" + request.term,
                cache: false,
                success: function(resp) {
                    try {
                        json = $.parseJSON(resp);
                    } catch (error) {
                        json = null;
                    }
                    //
                    if (json && json.status == "OK") {
                        //
                        response($.map(json.predictions, function(item) {
                            return {
                                label: item.description,
                                value: item.description
                            }
                        }));
                        //
                    }
                }
            });
        },
        minLength: 1,
        change: function (event, ui) {
            if (!ui.item){
                $(this).val("");
            }
        }
    });
相关问题