Search code examples
ruby-on-railshtmljquery-tokeninput

Jquery prepopulate data return null although data-pre html tag has expected values


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:

enter image description here

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:

enter image description here

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:

enter image description here

enter image description here

  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 enter image description here

parsing prepopulate with $.parseJSON does not help:

enter image description here

EDIT3

console log with $.parseJSON enter image description here


Solution

  • There were multiple issues with the original code.

    1. Prepopulation must always be done with a JSON array, not just an object as originally used.

    2. 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!