1. Introduction
Datepicker is a form of component that is familiar to you as a front-end, is a js library that supports creating datefields, daterange, widely used on many web applications. Its purpose is to display a calendar on a computer screen so that the user can easily select the date.
2. Implementation steps
Create project:
1 2 | rails new demo-datetimepicker |
Add gem file:
1 2 3 4 | gem 'momentjs-rails', '>= 2.9.0' gem 'bootstrap-sass', '3.3.7' gem 'bootstrap3-datetimepicker-rails', '~> 4.17.47' |
add file app / assets / javascripts / application.js
1 2 3 4 | //= require bootstrap //= require moment //= require bootstrap-datetimepicker |
Create another file: Touch app / assets / stylesheets / custom.scss and import:
1 2 3 4 | @import 'bootstrap-sprockets'; @import 'bootstrap'; @import 'bootstrap-datetimepicker'; |
Continue to add application.css file
1 2 3 | *= require bootstrap *= require bootstrap-datetimepicker |
create model:
1 2 | rails g model User name:string gender:string dob:datetime email:string address:string |
later
1 2 | rails db:migrate |
Add the routes file:
1 2 | resources :users |
Create file: Touch app / assets / javascripts / datetimepicker.js and add the following:
1 2 3 4 5 6 | $(function () { $('#datetimepicker').datetimepicker({ format: "DD/MM/YYYY" }); }); |
With the format: “dd / mm / YYYY”
1 2 3 4 5 | <div class="input-group date" id="datetimepicker"> <%= f.text_field :dob, placeholder: "Select the date and time", class: "form-control" %> <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span> </div></br> |
Add the following content to the datetimepicker.js file
1 2 3 4 5 6 | $('#datetimepicker').datetimepicker({ format: "DD/MM/YYYY" }); }); </script> |
When custom with format: only time
Add the following content to the datetimepicker.js file
1 2 3 4 5 6 7 | <script> $('#datetimepicker').datetimepicker({ format: "LT" }); }); </script> |
Custom with display field without icon
1 2 3 | <%= f.label :dob %> <%= f.text_field :dob, placeholder: "Select the date and time", id:"datetimepicker", class: "form-control" %> |
Change file datetimepicker.js
1 2 3 4 | $(function () { $('#datetimepicker').datetimepicker(); }); |
When Enabled / Disabled: to the default date: January 11, 2019, the current date: 12/20/2019 will be selected, the dates: 12/21/2019 and 12/22/2019 are disabled.
1 2 3 4 5 6 7 8 9 10 11 | $(function () { $('#datetimepicker').datetimepicker({ defaultDate: "11/1/2019", disabledDates: [ moment("12/20/2019"), new Date(2019, 11 - 1, 21), "11/22/2019 00:53" ] }); }); |
With the view mode displaying the year on the view, modify datetimepicker.js as follows:
1 2 3 4 5 | $(function () { $('#datetimepicker').datetimepicker({ viewMode: 'years' }); |
Above are the steps to add gem “bootstrap3-datetimepicker-rail” to the rails application. The article has many shortcomings that are looking forward to everyone’s comments.