Rails Assets error. Javascript not working correctly (Datepicker)

Asked

Viewed 296 times

0

I’m willing to add the bootstrap-datepicker to my project. I did it this way.

Gemfile:

source 'https://rails-assets.org' do
  gem 'font-awesome-sass',                  '~> 4.5.0'
  gem 'rails-assets-bootstrap-sass',        '~> 3.3.6'
  gem 'rails-assets-bootstrap-datepicker',  '~> 1.6.0'
end

_form.html.erb:

<div class="row">
   <div class="col-md-2">
      <%= f.input :publish_at, as: :string, input_html: { class: 'datepicker', 
            value: (Time.now + 1.day).strftime('%d/%m/%Y') } %>
   </div>
</div>

I created a file called datepicker.js within app/Assets/Avascripts:

$('.datepicker').datepicker({
  language: 'pt-BR',
  format: 'dd/mm/yyyy',
  startDate: '0d',
  autoclose: true,
  keyboardNavigation: false,
  todayHighlight: true
});
alert("hello");

The Alert is working, however it is as if I am not taking the '.datepicker' class from my _form.html.erb. When I put the same javascript code inside my _form.html.erb inside a script tag the datepicker perfectly pronounces, but I didn’t want to insert the script tag into each view that contains a datepicker.

1 answer

0

I recommend using the 'bootstrap-datepicker-Rails''.

In app/Assets/stylesheets/application.css, add:

*= require bootstrap-datepicker3

And in app/Assets/Javascripts/application.js

//= require jquery //= require jquery.turbolinks //= require jquery_ujs //= require turbolinks //= require bootstrap-datepicker //= require_tree .

And in your view

<input type="text" data-provide='datepicker' >

If you want to call the function via javascript put it inside:

$(document).ready(function(){ $('.datepicker').datepicker(); });

Also add to Gem 'jquery-turbolinks', '~> 2.1' if you use turbolinks

And that’s it, it should work. link to documentation

  • Eduardo, just through the data-provide attribute I won’t be able to edit some things from datepicker like the format, the language... as I put in my datepicker.js file. The solutions via Rails-Assets (Rails-Assets.org) are better than Gems. It wasn’t what I was looking for, but thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.