Question

I have jQuery token input implemented for tagging purposes where a user can search for a tag or create a new one thanks to railscasts ep#382 & ep#258. Data comes from the tags.json url which is the index action of the tags controller. The data from tags.json looks like so:

[
  {
    "created_at":"2013-06-21T16:30:19Z",
    "explanation":"hitting the hosel of the club",
    "id":8,
    "name":"shank",
    "updated_at":"2013-06-21T16:30:19Z",
    "updated_by":"andy"
  },
  {
    "created_at":"2013-06-22T17:40:37Z",
    "explanation":"hitting the ground before the ball",
    "id":12,
    "name":"chunk",
    "updated_at":"2013-06-22T17:40:37Z",
    "updated_by":"andy"
  }
]

My tags have a name as well as an explanation so I would like to include them in the results list like the Token and Results Formatting demo here http://loopj.com/jquery-tokeninput/demo.html#formatting.

The code below (number of entries omitted for brevity) is from the jQuery tokenInput Token and Results Formatting demo.

Instead of having "name": "Shank" manually entered here as well as the other omitted entries, how can I extract the name and explanation from tags.json hash and use them in the same was as the results formatter line, e.g. item.name & item.explanation?

tags.js

jQuery(function() {
var question = $('#question_tag_tokens')
  return question.tokenInput([{
       "name": "Shank",
       "explanation": "hitting the hosel of the club"
   }
 ], {
    propertyToSearch: ["name"],
    resultsFormatter: function(item){ return "<li>" + "<div class='tag' style='display:inline;color:#fff;'>" + item.name + "</div>" + " " + item.explanation + "</li>" },
    prePopulate: question.data('preload')
  });
});
Était-ce utile?

La solution

The source for the example you referred to goes like this:

 $(document).ready(function() {
     $("#demo-input-local-custom-formatters").tokenInput(
         [{
             "first_name": "Arthur",
             "last_name": "Godfrey",
             "email": "arthur_godfrey@nccu.edu",
             "url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png"
         },
         {
             "first_name": "Adam",
             "last_name": "Johnson",
             "email": "wravo@yahoo.com",
             "url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png"
         },
         ...

         ], 
         {
             propertyToSearch: "first_name",
             resultsFormatter: function(item){ ... },
             tokenFormatter: function(item) { ... }
         });
});

tokenInput seems to take an array of objects. Once you load the json with ajax, you just pass it in and tell it what field to search on and some callbacks to format the results.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top