如何使用jquery自动完成定义类型的参数?

时间:2014-06-04 05:40:55

标签: jquery jquery-ui autocomplete

我在这个不同的链接上有两个数据

链接1

/api/products?type=tour_package

数据1

[{"id":"-1","type":"tour_package","name":"Hello World"},
{"id":"1","type":"tour_package","name":"My title"}]

链接2

/api/products?type=nontour_product

数据2

[{"id":"-1","type":"nontour_product","name":"Korea Tickets"}]

我想在输入框中显示值

我的代码是

$('#product_name').autocomplete({ 
  source: function( request, response ) {
    url = "/api/products?type=" + request.term;

    $.getJSON( url , function(data) {
      response(data);
    });                 
  },
  minLength: 3, 
  select: function( event, ui ) {
    $($(this).data('target')).val(ui.item[ 'type' ]);
    $(event.currentTarget).val(ui.item[ 'name' ]);
  } 
});

HTML代码

<tr>
  <td><?= form_dropdown('product_type', array(
                          'custom' => 'Custom',
                          'tour_package' => 'Tour',
                          'nontour_product' => 'Generic',
                          'flight' => 'Flight',
                          'hotel_room' => 'Hotel'
                        )); ?>
  </td>
  <td><?= form_input(array('data-property'=>'product_name','style'=>'width:70px;','id'=>'product_name')) ?></td>
</tr>

1 个答案:

答案 0 :(得分:1)

访问链接的触发器取决于您的“product_type”下拉列表的更改,因此它可能会像这样......

$('#product_type').change(function(){
    var productType = $("#product_type").val();
    var url = "/api/products?type=" + productType;

    $('#product_name').autocomplete({
        source:url,
        minLength: 3,
        select: function( event, ui ) {

            $($(this).data('target')).val(ui.item[ 'type' ]);
            $(event.currentTarget).val(ui.item[ 'name' ]);
        }

    });
});