【问题标题】:jQuery UI autocomplete add selected item's description to a text fieldjQuery UI 自动完成将所选项目的描述添加到文本字段
【发布时间】:2012-10-30 13:25:41
【问题描述】:

我有以下自动完成文本框可以正常工作:

 $('#material_number').autocomplete({
     source: function(request, response) {
         $.ajax({
             url: "index.cfm?action=leadtime.getmaterialleadtime&returnformat=json",
             dataType: "json",
             data: {
                 search: request.term,
                 maxRows: 10
             },
             success: function(data) {
                 response(data);
                 console.log();
                 //need to append material_description to a textbox here
             }
         })
     }
 });

我想要输出返回到名为 txtMaterialDescription 的文本框的 material_description 值。我查看了此站点上的不同示例,但无法使其正常工作。因此,当用户从自动建议列表中选择零件号时,描述字段会填充零件号说明。任何人都可以帮助我并指出正确的方向吗?

一如既往的感谢。

JC

【问题讨论】:

    标签: jquery ajax json jquery-ui jquery-ui-autocomplete


    【解决方案1】:

    您需要捕获focus 或select 事件:

    focus: function(event, ui) {
        $("#textbox").val(ui.item.someProperty);
    }
    

    现在,如果您的 JSON 数据包含看起来像 {label: ..., value: ..., someProperty: ...} 的对象,那么您可以编写:

    source: function(request, response) {
        $.ajax({
            url: "index.cfm?action=leadtime.getmaterialleadtime&returnformat=json",
            dataType: "json",
            data: {
                search: request.term,
                maxRows: 10
            },
            success: response
        });
    }
    

    否则,您始终可以使用jQuery.map 转换您的数据:

    source: function(request, response) {
        $.ajax({
            url: "index.cfm?action=leadtime.getmaterialleadtime&returnformat=json",
            dataType: "json",
            data: {
                search: request.term,
                maxRows: 10
            },
            success: function(data) {
                response($.map(data, function(item) {
                    return {
                        label: item.productName,
                        value: item.productCode,
                        someProperty: item.productDescription + item.productPrice
                    }
                }));
            }
        });
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用焦点选项并为重点项目加载详细信息,例如

         focus: function(event, ui) {
                  $(this).val(ui.item.label);
      
       //do ajax call here  for currently focused element 
        // and on sucesss you can do the following
      
        //add your detail description here
                  $("#tags").empty();
                  $("#tags").append("Detailed for "+ui.item.label);
      
                  return false;
              },
      

      详细解释可以看这里-jquery autocomplete example

      【讨论】:

        猜你喜欢
        • 2011-08-08
        • 2011-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多