2014-03-14 76 views
1

我正在嘗試爲城市查找實現typeahead,但該字段沒有更新。城市細節顯示出來,但我需要在城市點擊時在城市中顯示該名稱,但是當表單發送時,我只需要發送城市代碼。typeahead not updating field

這是我的HTML:

<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " /> 

這是JavaScript:

$('#_hotelCity').typeahead({ 
    source: function (query, process) { 
     airports = [];  
     map = {}; 
     var data = (function() { 
      var data = null; 
      $.ajax({ 
       'async': false, 
       'global': false, 
       'url': 'http://localhost/imakeway/forms/finder/iata-aero-codes.json', 
       'dataType': "json", 
       'success': function (jdata) { 
        data = jdata; 
       } 
      }); 
      return data; 
     })(); 

     $.each(data, function (i, airport) { 
      map[airport.complete_location] = airport; 
      airports.push(airport.city + ' (<b>' + airport.iata_code + '</b> - ' + airport.airport_name + ') near ' + airport.complete_location); 
     }); 

     process(airports);  
    }, 
    updater: function (item) { 
     selectedairport = map[item].complete_location; 
     selectedairport = map[item].iata_code; 
     return item; 
    }, 
    matcher: function (item) { 
     if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) { 
      return true; 
     } 
    }, 
    sorter: function (items) { 
     return items.sort(); 
    }, 
    highlighter: function (item) { 
     var regex = new RegExp('(' + this.query + ')', 'gi'); 
     return item.replace(regex, "<strong>$1</strong>"); 
    }, 
}); 

謝謝你的任何建議

+1

你使用的是什麼版本的typeahead.js? typeahead.js沒有「updater」,「matcher」,「sorter」或「highlighter」選項。 –

回答

0

HTML input標籤只能有一個值。該值存儲在內部並顯示在該字段內。

看來你正在使用某種AJAX表單提交。 所以,你的解決方案是在JS中有單獨的變量來存儲城市代碼。

另一種解決方案是使用Select2而不是鍵入。 當您提供類似於SELECT的字段但需要外部AJAX數據源時,這是我的選擇。 順便說一句,與選擇2,你也可以強制用戶只選擇一個現有的價值。

看吧例如:http://ivaynberg.github.io/select2/#ajax

0

我會建議你使用你更新拋開正常的輸入字段附加hidden場。

<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " /> 
<input type="hidden" value="" name="city_code" /> 

在這個隱藏字段中,每當更新typeahead時都會插入城市代碼。提交表單時,服務器端腳本可以解析它(在PHP中,它將爲$_POST['city_code'])。

0

使用typeahead,並不想取代你的代碼。我結束了與此琴:http://jsfiddle.net/Ydtq9/2/

你一定會想重構一些東西,但關鍵是要設置一些實例變量在源功能,您可以訪問他們在更新功能,像這樣

$("#_hotelCity").typeahead({ 
    "source": function(query, process) { 
    this.map = ... 
    }, 
    "updater": function(item) { 
    var city = this.map(item) 

    //Then you can do what you need to with the original data. 
    } 
})