2016-04-14 88 views
0

我想在用户插入正确值并转义输入字段时自动填充输入字段。这方面的一个例子是https://www.redbus.in/ 我使用url字符串发送数据请求,并在那之后收到结果。我想继续发送数据请求并接收结果,即使用户退出该字段?然后,必须选择结果列表的第一个值。不是你的帮助!带聚焦输出解决方案的jQuery自动完成

我的代码是:

jQuery(document).ready(function(){ 
    jQuery("#econt_offices_town").autocomplete({ 
     minLength: 2, 
     autoFocus: true, 
     source: function(request, response) { 
      jQuery.ajax({ 
       url: ajaxurl, 
       dataType: "json", 
       data: { 
        action:'handle_ajax', 
        city: request.term 
       }, 
       success: function(data) { 
        response(jQuery.map(data, function(item) { 
            return { 
             label:  item.label, 
             value:  item.value, 
             city_id: item.id, 
             post_code: item.post_code   
            }; 
          })); 
       }, //end of success 
      }); //end of ajax 
     }, //end of source 
     select: function(event, ui) { 
      var city_id = ui.item.city_id; 
      var post_code = ui.item.post_code; 
      jQuery('#econt_offices_postcode').val(post_code); 
      jQuery('#office_locator').show(); //show office locator button after the city is selected 
      jQuery('#econt_offices_postcode, label[for="econt_offices_postcode"], #econt_offices, label[for="econt_offices"]').show(); 
      jQuery.ajax({ 
       url: ajaxurl, 
       dataType: "json", 
       data: { 
        action:'handle_ajax', 
        office_city_id: city_id, 
        delivery_type: 'to_office' 
       }, 
       success: function(data) { 
        jQuery('#econt_offices').empty() 
        jQuery.each(data, function(key, value) { 
         jQuery('#econt_offices').append(jQuery("<option/>", { 
           value: value.id, 
           text: value.value + ' [о.к.:' + value.id + ']' 
         })); 
        }); 
        calculate_loading(); //calculate loading cost for shipping to office 
       } //end of success 
      }); //end of ajax 
     }, //end of select 
    }); //end of #econt_offices_town .autocomplete 
+0

只是一个侧面说明,但是这看起来像一个很好的例子为一类:'的jQuery('#econt_offices_postcode,标签[为=‘econt_offices_postcode’],# econt_offices,label [for =“econt_offices”]')。show();''如'jQuery('。postcodethings')。show();' –

回答

0

尝试添加一些额外的事件管理与一些创造性的使用。

如果我知道你要选择当有人标签页拖出或点击其他地方的值(聚焦丢失)

$("#econt_offices_town").on('keydown focusout', function(event) { 
    if (event.keyCode != $.ui.keyCode.TAB && !(event.type == "focusout")) return; 

    event.keyCode = $.ui.keyCode.DOWN; 
    event.type = "keydown";//change the event from focusout 
    $(this).trigger(event); 

    event.keyCode = $.ui.keyCode.ENTER; 
    $(this).trigger(event); 
}); 
0

我知道了。这是如何自动选择列表中只有一个值。我把这段代码“源”与“选择”

response: function(event,ui) { 
      if (ui.content.length == 1) { 
       ui.item = ui.content[0]; 
       jQuery("#econt_offices_town").data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui); 
       jQuery("#econt_offices_town").autocomplete('close'); 
      } 
     },