setting minDate in datepicker in Rails - javascript

I need to apply minDate attribute to the datepicker in Rails App as today's date.
In _admin_controls.html.erb
<%= f.input :end_date, wrapper: :append do %>
<div id="datepicker" class="datepicker input-group edit-left">
<%= f.text_field :end_date, :class => "datetime form-control" %>
application.js contains
jQuery(document).on('focus', 'input.datetime', function() {
opts = {format: 'M dd, yyyy', autoclose: true};
jQuery(this).datepicker(opts);
jQuery(".datepicker").css("z-index",10000);
});
What should be the javascript to do so only for _admin_controls.html.erb?

If You are using Jquery then you can set the date like this :
// If you want to set a date then assign it to a variable or create a function and call that function directly.
var currentDate = new Date();
$("#mydate").datepicker().datepicker("setDate", new Date());

I have been able to solve the problem.
In application.js, I removed the code related to datepicker and its librariies and created a new file datepicker.js
datepicker.js contains
/* bootstrap datepicker */
//= require bootstrap-datepicker/core
//= require bootstrap-datepicker/locales/bootstrap-datepicker.es
jQuery(document).on('focus', 'input.datetime', function() {
opts = {format: 'M dd, yyyy', autoclose: true};
jQuery(this).datepicker(opts);
});
In application.js
//= require datepicker
In _admin_controls.html.erb,
<%= f.input :end_date, wrapper: :append do %>
<div id="datepicker" class="datepicker input-group edit-left">
<%= f.text_field :end_date, :class => "datetime form-control", :'data-date-start-date' => Date.current.strftime('%m/%d/%Y') %>
And this disables backdate selection for particularly _admin_controls datepicker. :)

This should do it
$('#start_date').datepicker({
minDate: 0,
onSelect: function (selected) {
$("#end_date").datepicker("option", "minDate", selected)
}
});
Where end date being the one in the other box which allows to select the max one .

You can set the rails input field to the following:
<%= f.datetime_local_field(:end_date, min: Time.now().to_s.slice(0,10) ) %>

Related

Jquery .on change() hitting both all select fields in js.erb file ruby on rails

I am new to Javascript and Jquery in Rails so apologies if something like this has been asked before. I have been stuck on this issue all day now.
I have three fields in a form, "from location," "to location," and "quantity". When the "from location" select field is changed, I'd like for:
the "to location," to change to remove the selected field in the "from location"
the "quantity" to reflect the available quantity at the "from location."
I am writing this in my edit.js.erb file for my item model.
I have given all fields different classes and am referencing the specific field by class but the .on change() is firing for all select fields.
(The variable fohInventoryItems is provided via a script block in this model's index page.)
Here's my code:
var selectedItemClass = <%=#item.id%>
(document).on('change', $('select.' + selectedItemClass + "." + 'from-select').eq(0), function() {
});
And her is my code in _form.html.erb for this model:
<%= form_for item, remote: true, format: "js" do |f| %>
<%= f.label :from_location %><br>
<%= f.collection_select :location_ids, item.locations.uniq, :id, :name, {selected: item.locations.uniq.first}, { class: "form-control #{item.id} from-select", } %><br>
<%= fields_for :line_items, item.line_items.build do |l| %>
<%= l.label :to_location %><br>
<%= l.collection_select :location, Location.all, :id, :name, {}, { class: "form-control #{item.id} to-select" } %><br>
<%= f.label :quantity %><br>
<%= f.select :quantity, (Array (1..item.quantity)), {}, { class: "form-control #{item.id}" } %>
<%end%>
<br>
<div style="text-align: center;">
<%= f.submit "Move", class: "#{item.id} submit" %><br>
</div>
<% end %>
When using on() as a delegated event handler, the second argument is used as a filter internally to check if the elements match a selector.
The documentation clearly states that the syntax is
.on( events [, selector ] , handler )
With seleector being
selector
Type: String
A selector string to filter the descendants of
the selected elements that will call the handler. If the selector is
null or omitted, the handler is always called when it reaches the
selected element.
The reason for it being a string, is that the elements will be checked against it, so it can't be another jQuery collection.
...meaning you have to change your code to
$(document).on('change', '.' + selectedItemClass + 'from-select', function() {...

DateTimePicker not updating values on ruby side

I am having an issue where the regular datepicker updates the value on the rails side in this format '2017-09-12 22:49:27', but I am trying to use datetimepicker and its not updating the value, it updates the text field with the format: M/DD/YYYY but not the actual value in the param as I need that in '2017-09-12 22:49:27' format but its staying the same value which is currently MM/DD/YYYY as what's loaded up for the text field and I am getting an undefined value when I try to see the current value:
var selectedDate = $("#from").find(".active").data("day");
Here is the ruby code
= text_field_tag :from_js, l((params[:from].to_datetime or #item.created_at), format: :american_no_time), class: 'form-control input-sm datetimepicker', id: 'from'
= hidden_field_tag :from, l((params[:from].to_datetime or #item.created_at), format: :american_no_time)
= text_field_tag :to_js, l((params[:to].to_datetime or Time.zone.now.to_datetime), format: :american_no_time), class: 'form-control input-sm datetimepicker', id: 'to'
= hidden_field_tag :to, l((params[:to].to_datetime or Time.zone.now.to_datetime), format: :american_no_time)
and here is the current javascript:
var maxDate = new Date();
var minDate = $("#from").val();
$(function () {
$('#from').datetimepicker({
format: "M/D/YYYY",
minDate: minDate,
maxDate: maxDate,
pickTime: false
});
$('#to').datetimepicker({
format: "M/D/YYYY",
minDate: minDate,
maxDate: maxDate,
pickTime: false
});
});
Any ideas or suggestions would be appreciated

Datepicker change date value and formatting rails 4

I've made form to change date or city, but datepicker doesn't work properly. Here is link: http://leszczyna.wzks.uj.edu.pl/12_stolarski/events_for_seniors/pl/events?utf8=%E2%9C%93&search=Krak%C3%B3w&start_date=11-06-2015
Problem is with datepicker, when you click on it, it changes date to another format and year is set to 1911.
Here is my js:
$('document').ready(function() {
if ($('body.events').length) {
/* Datepicker for changing date in events */
$('.date').datepicker({
'language': "pl",
'todayHighlight': true,
'format': 'dd-mm-yyyy',
'autoclose': true
})
}
And part of my erb file
<div class="form-group">
<label class="sr-only" for="date">Email</label>
<%= text_field_tag :start_date,
params[:start_date],
placeholder: 'Kliknij, aby wybrać datę',
class: 'form-control date',
:data => {
provide: 'datepicker'
}
%>
</div>
You have kept your format as dd-mm-yyyy, but your param :start_date holds value in wrong order. If you want to set come default date, I will suggest you to use defaultViewDate option. Your calendar dates (which opens up initially) are disabled, that's why it selects some 1911 year date. try using startDate and endDate option. I hope it will fix it.

How to Change Date Format According to User Selection?

How can I change the date :order according to the User's "f.select :categories" choice?
For example when a User goes to the Quantified _form he can select between "Monthly Average" or "One-Time Instance";
If he selects "Monthly Average" I want the _results_fields.html.erb to provide the date selection as ":order => [:month, :year]" if he selects "One-Time Instance" I want the _results_fields.html.erb to provide the date selection as ":order => [:month, :day, :year]
Ideally this would be done dynamically via javascript, but I would be happy to accept an answer that does it via the view.
_results_fields.html.erb
<div class="nested-fields">
<div class="form-group">
<%= f.text_field :result_value, class: 'form-control', placeholder: 'Enter Result' %>
<br/>
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select' %>
<%= link_to_remove_association "Remove Result", f %>
</div>
</div>
_form.html.erb
<%= form_for #quantified do |f| %>
<div class="america">
<%= f.select :categories, Quantified::CATEGORIES %>
<br/>
<br/>
<div class="form-group">
<%= f.text_field :name, class: 'form-control', placeholder: 'Enter Name' %>
</div>
<div class="form-group">
<%= f.text_field :metric, class: 'form-control', placeholder: 'Enter Metric' %>
</div>
<div id="results">
<%= f.fields_for :results do |result| %>
<%= render 'result_fields', :f => result %>
<% end %>
</div>
<div class="links">
<%= link_to_add_association 'add result', f, :results %>
</div>
<%= f.submit %>
</div>
<% end %>
quantified.rb
class Quantified < ActiveRecord::Base
belongs_to :user
scope :averaged, -> { where(categories: 'Monthly Average') }
scope :instance, -> { where(categories: 'One-Time Instance') }
has_many :results
accepts_nested_attributes_for :results, :reject_if => :all_blank, :allow_destroy => true
CATEGORIES = ['Monthly Average', 'One-Time Instance']
end
Github: https://github.com/RallyWithGalli/ruletoday
Thank you for your time.
The answer here was to use some jquery provided by the gem that was being used to add the date selects, as well as some jquery of our own
First things first, we rig up the checkboxes with a click() event, that hides anything with the class 'day' if instance is checked, and shows it if not.
$('.date-toggle').click(function(){
if( $(this).attr('id') == 'instance') {
$('.day').show();
} else {
$('.day').hide();
}
});
The trick here is to use the rails date select option :with_css_classes on the date select, so that it looks like this:
<%= f.date_select :date_value, :order => [:month, :day, :year], :with_css_classes => true, class: 'date-select' %>
This causes each included field to get a class corresponding to its name, hence our reference to '.day' up there.
The next important part, however, because he is using a gem called cocoon to add new elements that included date fields, we had to use some of their jquery event bindings to make sure that the new ones got the right action applied to them.
$('#container').on('cocoon:after-insert', function(e, insertedItem) {
if($('#instance').is(':checked')) {
$('.day').show();
} else {
$('.day').hide();
}
});
Technically, the $('.day').show() is not necessary, because it defaults to being shown, but this, to me, gets across the intent a little clearer.
I think my solution is a little bit messy, but hopefully it gives you an indication of my train of thought and give you something to build upon.
I have changed your categories to work with a radio button group because the select field is a bit weird for 2 elements (subjective I know), to change it back to a select form,simply keep your code as is, but you will need to check the value of the select dropdown using jQuery .change() or some other vanilla Javascript way...
You haven't provided any controller names, so I didn't know how to name my JS file, but hopefully you know how to integrate.
IMO, I'm not sure why this needs AJAX, so maybe you can explain to me where that comes in.
_form.html.erb
<%= Quantified::CATEGORIES.each do |c| %>
<%= f.radio_button(:category, c) %>
<%= label(c, c) %>
<% end %>
_results_fields.html.erb
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select-my' %>
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select-mdy' %>
vanilla.js
$(document).ready(function(){
$('.date-select-mdy').hide();
$('.date-select-mdy').attr("disabled", true);
$('input[name$=\category\']').click(function() {
var target_value;
target_value = $(this).val;
if (target_value === 'Monthly Average') {
$('.date-select-my').show();
$('.date-select-mdy').hide();
$('.date-select-my').attr("disabled", false);
return $('.date-select-mdy').attr("disabled", true);
} else {
$('.date-select-my').hide();
$('.date-select-mdy').show();
$('.date-select-my').attr("disabled", true);
return $('.date-select-mdy').attr("disabled", false);
}
});
});
a_little_bit_of_coffee_because_i_dislike_js.coffee
$->
$('.date-select-mdy').hide()
$('.date-select-mdy').attr("disabled",true)
$('input[name$=\category\']').click ->
target_value = $(this).val
if target_value == 'Monthly Average'
$('.date-select-my').show()
$('.date-select-mdy').hide()
$('.date-select-my').attr("disabled",false)
$('.date-select-mdy').attr("disabled",true)
else
$('.date-select-my').hide()
$('.date-select-mdy').show()
$('.date-select-my').attr("disabled",true)
$('.date-select-mdy').attr("disabled",false)
return

how to resolve date picker format in mvc5

Im working in MVC5 entity framework. Here some fields have date fields so I need to set data format. Here I using script and datepicker. Now I got a problem if I set after date of 12. I got error like "enter valid date"
Script used in views:-
$('#datepick').datepicker({
dateFormat: 'dd/mm/yy', minDate: 0
});
Code used in views
<div class="row form-group">
<div class="col-md-4">
Due Date:
</div>
<div class="col-md-8">
#Html.TextBoxFor(model => model.goodreceipt.Due_Date, new { #Value = DateTime.Now.ToString("MM/dd/yyyy"), #class = "form-control control-text ", #id = "datepick" })
#*#Html.ValidationMessageFor(model => model.goodreceipt.Due_Date)*#
</div>
</div>
I got error Like this"Enter valid date" the date must be with in 12, after 12 (i.e 13-12-2014) error will occur so onlyIi comment validation message but here I itself I got this error.
Here i want to finish this task.
I guess there are different format of date..need some change as below and try again :-
$('#datepick').datepicker({ dateFormat: 'MM/dd/yyyy', minDate: 0 });

Categories

Resources