using tokeninput jquery plugin on more than one in

2019-07-16 04:33发布

问题:

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.