简体   繁体   中英

Using the same JQuery tokeninput box multiple times on a page

I am using Jquery TokenInput in my rails app to help users quickly input information. Each user has a profile with many items of the same class on it, call them college_items. Each college_item has its own edit link, which pops up a modal with the appropriate edit form for the modal.

I followed Ryan Bates's screencast and got TokenInput working properly using the following code:
In application.js:

$(function() {
 $("#education_major_tokens").tokenInput("/majors.json", {
   theme: "facebook"
  })
});

In my view:

<%= f.text_field :major_tokens %>

In my model:

def major_tokens=(ids)
 self.major_ids = ids.split(",")
end


The problem I'm running into is that this same field appears in each edit form, so in the edit form for the first item everything works perfectly, but in the edit form for any other item the javascript is not initialized. My question is how can I change the javascript to initialize each time this form element appears, not just the first?

EDIT: I thought something like this might be the solution:

$(function() {
 $("#education_major_tokens").each(function(){
   $(this).tokenInput("/majors.json", {
   theme: "facebook"
   })
  });
});

but it still isn't working for me. Anyone out there have any ideas?

EDIT 2: Figured this out finally. See my edit above, only instead of using #education_major_tokens, I set each input to have:class => "major_input" and changed "#education_major_tokens" in the code to ".major_input"

I think this is a bit late, but try to assign a class to your token field

<input class="yourtokenfield" type="text" />

After that use this

$(function() {
 $(".yourtokenfield").each(function(){
   $(this).tokenInput("/majors.json", {
   theme: "facebook"
   })
  });
});

I think your problem is due to improper name for class, and remember ID must only appear once in your HTML document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM