sealocal
sealocal

Reputation: 12417

How do I initialize Bootstrap Tagsinput with Ruby on Rails and Bootstrap 3

Background and Tools:

I am using the Bootstrap Tags Input jQuery plugin with Rails.

I am storing the plugin as vendor/assets/javascripts/bootstrap-tagsinput.js and it's stylesheet as vendor/assets/stylesheets/bootstrap-tagsinput.css.

I am tagging all of my Books in a digital library Rails app.

Problem:

If I navigate directly to Book#new or Book#edit, tags work as expected from the project's demo page.

However, if I navigate to the Books#edit or Books#new page via a link click on another page, then my text input is formatted as a typical html text input with the comma-separated string science,fiction,good,short displayed.

More Info: My input looks like this:

<input class="form-control tagsinput" data-role="tagsinput" id="books_tags"
name="books[tags]" type="text" value="science,fiction,good,short">

The bootstrap-tagsinput.js file has these lines at the bottom of the file:

  /**
   * Initialize tagsinput behaviour on inputs and selects which have
   * data-role=tagsinput
   */
  $(function() {
    $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();
  });
})(window.jQuery);

It seems that this initialization gets run by Rails and applies it's JavaScript magic to the <input> when entering a URL location directly, but not when navigating via links on pages.

Question:

How do I get the initialization to run when navigating from another page?

Upvotes: 1

Views: 3382

Answers (1)

sealocal
sealocal

Reputation: 12417

Placing the initialization code in app/assets instead of vendor/assets will run the initialization on page load. The bootstrap-tagsinput.js library will still be loaded via vendor/assets, but the initialization will need to be run via app/assets.

Remove theses lines from vendor/assets/javascripts/bootstrap-tagsinput.js:

  $(function() {
    $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();
  });

and place them in a JS file inside the asset pipeline: app/assets/javascripts/books.js.

  $(function() {
    $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();
  });

Moving the content will ensure that the initialization runs. Do not simply copy the lines over, or the initialization will run twice - and that will really mess up the appearance of your nifty tagsinput plugin.

Upvotes: 3

Related Questions