为什么jQuery自动完成选择不起作用?

时间:2014-09-08 04:27:17

标签: javascript php jquery

当我在customer_code输入区输入5时。它列出了值。问题是,当我选择一个条目时,'id'值应显示在customer_name区域。但它没有!

[{"id":"5","code":"code005","name":"\u9867\u5ba2\u540d005"},{"id":"15","code":"code015","name":"\u9867\u5ba2\u540d015"},]

php的json返回就像上面那样。并且

$(function() {
        $( "#customer_code" ).autocomplete({
        source:  function( request, response ) {
            $.ajax({
                url: "/management/order/auto",
                dataType: "json",
                data: {code: request.term},
                success: function(data) {
                     var suggestions = [];
                    $.each(data, function(i, val) {
                        suggestions.push({
                            label: val.code,
//                          label: val.name,
                        });
                    });
                    response( suggestions );
                },
            });
        },
        select: function(e, ui) {
            alert(ui.item.name);
//          $('#customer_name').val(ui.item.name);
//          $('#customer_name').val(ui.item.value.name);
//          return false;
        },
        });
    });

我的html页面就像这样

<?php echo Form::input('customer_name', Arr::get($basic, 'customer_name'), array('id' => 'customer_name')); ?>
<?php echo Form::input('customer_code', Arr::get($basic, 'customer_code'), array('id' => 'customer_code')); ?>

1 个答案:

答案 0 :(得分:0)

select回调当前是$.ajax()请求设置的一部分,该请求不会使用它:

// ...
    $.ajax({
        url: "/management/order/auto",
        // ...
        success: function (data) {
            // ...
        },
        select: function (e, ui) {
            // ...
        }
    });
// ...

它应该是.autocomplete()的选项的一部分,function之外的source

$( "#customer_code" ).autocomplete({
    source: function( request, response ) {
        $.ajax({
            url: "/management/order/auto",
            // ...
            success: function () {
                // ...
            }
        });
    },
    select: function (e, ui) {
        // ...
    }
})