I am using Jquery token input plugin to for autocomplete and prepopulating data.
Autocomplete looks fine, but I do have some problems with prepopulating data.
This is my javascript:
tokenOptions = {
theme: 'facebook',
searchingText: null,
hintText: null,
noResultsText: null,
allowFreeTagging: true,
tokenValue: 'name',
searchDelay: 1000,
prePopulate: $('#citizen_profile_attributes_city').data('pre')
}
$(document).ready ->
console.log('prepopulate:' + tokenOptions.prePopulate)
$("#citizen_profile_attributes_city").tokenInput("/cities.json",
tokenOptions )
This is a part of form(in HAML):
= f.text_field :city, :data => { 'pre' => @profile.pre_populate_city } , :id => 'citizen_profile_attributes_city'
This is method pre_populate_city:
def pre_populate_city
city_name = self.city
city_id = (City.find_by_name city_name).id
{ "id" => city_id, "name" => city_name}.to_json
end
This is returned html:
As you can see, in html there a data attribute with correct values, but I do not see them in prepopulated area.
In my javascript I used console log to see the output, it return null, when I try to query this id in console, I do get desired attributes:
The question is - what is wrong with this code ?
Note: I do tried to change id in jquery for #token-input-citizen_profile_attributes_city
as well.
EDIT After wrapping and object into array, pre populating works, but it prepopulates with undefined:
def pre_populate_city
city_name = self.city
city_id = (City.find_by_name city_name).id
[{ "id" => city_id, "name" => city_name}.to_json]
end
EDIT2
parsing prepopulate with $.parseJSON does not help:
EDIT3
console log with $.parseJSON
There were multiple issues with the original code.
Prepopulation must always be done with a JSON array, not just an object as originally used.
The second issue was with the encoding of resultant encoding of the JSON in the data-pre
attribute. The JSON must be HTML encoded, that is, quotation marks replaced with "
.
For clarification, this is what the data-pre
attribute should look like in the above situation, I image rails has some method to automatically html encode strings.
data-pre="[{"id":2368,"name":"Tokajík"}]"
The Updated Fiddle shows a fully working version. Note that the data does not need to be JSON-parsed as previously suggested in comments, my mistake. Hope this helps!