using tokeninput jquery plugin on more than one input on a page

我怕爱的太早我们不能终老 提交于 2019-12-12 19:09:24

问题


I'm using the jquery tokeninput plugin from loopj.com Here is my JS File:

$(document).ready(function() {

    // Token input plugin:

    $("#issuer").tokenInput("/issuers.json",{
        crossDomain: false,
        theme: "facebook",
        prePopulate: $("#issuer").data("pre"),
        preventDuplicates: true
    });

    $("#shareholder").tokenInput("/shareholders.json",{
        crossDomain: false,
        theme: "facebook",
        prePopulate: $("#shareholder").data("pre"),
        preventDuplicates: true
    });

});

Here is my Markup:

<form method="post" action="/certificates" accept-charset="UTF-8">
<input type="hidden" value="✓" name="utf8">
<input type="hidden" value="fSO/GJxIGEHLCb/zmd1B7qTwUYnGx5yyIxWTkEk/ies=" name="authenticity_token">\

  <div class="field">
    <label for="issuer">Issuer</label><br>
    <input type="text" size="30" name="certificate[issuer]" id="issuer" data-pre="[null]">
  </div>

 <div class="field">
    <label for="shareholder">Shareholder</label><br>
    <input type="text" size="30" name="certificate[shareholder]" id="shareholder" data-pre="[null]">
  </div>
</form>

My tokenize plugin works on #issuer but not #shareholder, if i move the jQuery code with #shareholder selector at the top the Token Input code works for the #shareholder but stops working for the other one. How can i have it work for both of them??

Also, if i have the same form with the same markup in edit mode - which means data-pre has a valid JSON instead of [null], Token Input works for both of these fields.


回答1:


I don't really know why it doesn't work for you. I usually use this script to add tokenInput to multiple fields:

$(".token_input").each(function(){
  var el = $(this);
  el.tokenInput(el.data("url"), {
    crossDomain: false,
    theme: "facebook",
    prePopulate: el.data("pre"),
    preventDuplicates: true
  });
});

It's important to add token_input as a class and a data-url attribute to the input fields. Here's how I'd do it (in Rails):

<%= f.text_field :issuer_tokens, :class => "token_input", "data-url" => "/issuers.json", "data-pre" => @certificate.issuers.map(&:attributes).to_json %>
<%= f.text_field :shareholder_tokens, :class => "token_input", "data-url" => "/shareholders.json", "data-pre" => @certificate.shareholders.map(&:attributes).to_json %>

Hope it works for you. If it doesn't work, try downloading a new version of tokenInput.



来源:https://stackoverflow.com/questions/6092279/using-tokeninput-jquery-plugin-on-more-than-one-input-on-a-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!