JQuery datepicker language not working correctly - javascript

I using jquery datepickers in my project and need to have local language on it.
I need to pass language from back end via gon.locale(rails stuff)
So here is my ts code
const search_legs_1_datepicker = $("#search_legs_1_datepicker");
var leg_1_datepicker = $("#search_legs_1_datepicker").datepicker({
language: gon.locale,
classes: 'inline-picker',
altField: '#search_legs_1_date',
defaultDate: new Date(search_legs_1_datepicker.attr("data-defaultDate")),
minDate: new Date(search_legs_1_datepicker.attr('data-mindate')),
maxDate: new Date(search_legs_1_datepicker.attr('data-maxdate')),
altFormat: 'yy-mm-dd',
onSelect: (formattedDate, date, inst) => {
if ($("#search_legs_1_hotel_date").length > 0) {
$('#search_legs_0_hotel_date').datepicker().data('datepicker').update('maxDate', date);
$('#search_legs_1_hotel_date').datepicker().data('datepicker').update('maxDate', date);
$('#search_legs_1_hotel_date').datepicker().data('datepicker').datepicker("setDate", date);
}
}
})
I checked gon.locale with console and get sv-SE so it's pass language.
Also I try to do it like this
language:"sv-SE"
It not works too.
But for some reasons I have en at my datepickers.
Where is my problem?

Check that you have the language file.
Datepicker provides support for localizing its content to cater for
different languages and date formats. Each localization is contained
within its own file with the language code appended to the name, e.g.,
jquery.ui.datepicker-fr.js for French. The desired localization file
should be included after the main datepicker code. Each localization
file adds its options to the set of available localizations and
automatically applies them as defaults for all instances.
http://api.jqueryui.com/datepicker/
Localization files can be found there : https://github.com/jquery/jquery-ui/tree/master/ui/i18n

You need to include language file and then set the default language as "sv".
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>
Date Picker on input field: <input type="text" id="search_legs_1_datepicker" name="date1"/>
const search_legs_1_datepicker = $("#search_legs_1_datepicker");
var leg_1_datepicker = $("#search_legs_1_datepicker").datepicker({
//language: gon.locale,
classes: 'inline-picker',
altField: '#search_legs_1_date',
defaultDate: new Date(search_legs_1_datepicker.attr("data-defaultDate")),
minDate: new Date(search_legs_1_datepicker.attr('data-mindate')),
maxDate: new Date(search_legs_1_datepicker.attr('data-maxdate')),
altFormat: 'yy-mm-dd',
onSelect: (formattedDate, date, inst) => {
if ($("#search_legs_1_hotel_date").length > 0) {
$('#search_legs_0_hotel_date').datepicker().data('datepicker').update('maxDate', date);
$('#search_legs_1_hotel_date').datepicker().data('datepicker').update('maxDate', date);
$('#search_legs_1_hotel_date').datepicker().data('datepicker').datepicker("setDate", date);
}
}
})
$.datepicker.setDefaults($.datepicker.regional['sv']);
This file supports all languages - "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"
If you want to include specific file then get the specific langauge file from here https://github.com/jquery/jquery-ui/tree/master/ui/i18n.

Related

Pick a date range in single Bootstrap Datepicker

I am using Bootstrap DatePicker v1.8.0
Need to select range in a single bootstrap and I need the input value to be arranged in ascending order (example below).
On changing the date, the date array is appended with the new date. Get the dates and parse it in changeDate event listener and set it again.
$('#date').datepicker({
format: "M yyyy",
startView: 1,
minViewMode: 1,
maxViewMode: 2,
multidate: true,
multidateSeparator: "-",
autoClose:true,
}).on("changeDate",function(event){
var dates = event.dates, elem=$('#date');
if(elem.data("selecteddates")==dates.join(",")) return; //To prevernt recursive call, that lead to lead the maximum stack in the browser.
if(dates.length>2) dates=dates.splice(dates.length-1);
dates.sort(function(a,b){return new Date(a).getTime()-new Date(b).getTime()});
elem.data("selecteddates",dates.join(",")).datepicker('setDates',dates);
});
function getDates()
{
console.log($("#date").datepicker("getDates"));
console.log($("#date").datepicker("getUTCDates"));
console.log($("#date").data('datepicker').getFormattedDate('yyyy/mm'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" rel="stylesheet"/>
<input type="text" id="date"><button onclick="getDates()">Get Dates</button>
To get the dates,
$("#date").datepicker("getDates") - Returns an array of selected start and end dates in local time.
$("#date").datepicker("getUTCDates") - Returns an array of selected start and end dates in UTC time.
$("#date").data('datepicker').getFormattedDate('yyyy/mm') - Returns the concatenation of start and end dates as strings formatted to the given format and joined by the multidateSeparator.

Option disabledDates from bootstrap datetimepicker not working

I'm using the bootstrap datetimepicker for my calendar. My code looks like this:
var sundaysDisabled = [
moment("17/12/2017"),
moment("7/1/2018"),
moment("14/1/2018"),
moment("21/1/2018"),
moment("28/1/2018"),
moment("4/2/2018")
];
$("#form_dateTakeout").datetimepicker({
inline: true,
format: 'L',
daysOfWeekDisabled: daysDisabled,
disabledDates: sundaysDisabled,
date: selectDate,
minDate: tomorrow
});
I've found the option disabledDates in the documentation.
The problem is I can still select these days, I'm only getting this warning:
But I think that it can't be the problem, am I right?
You are getting Deprecation Warning because your date string are not in a recognized format (ISO 8601 or RFC 2822), you have to use moment(String, String). In your case, you can have something like moment("17/12/2017", 'D/M/YYYY').
To set a default date to the datetimepicker, use defaultDate option instead of date (the first is documented while the latter isn't, even if it seems that both work).
Be sure that your defaultDate, minDate, disabledDates and daysOfWeekDisabled are coherent, see also useCurrent docs.
Set the defaultDate to an enabled date to prevent something like:
Uncaught Tried 7 times to find a valid date
Here a full example:
var sundaysDisabled = [
moment("17/12/2017", 'D/M/YYYY'),
moment("7/1/2018", 'D/M/YYYY'),
moment("14/1/2018", 'D/M/YYYY'),
moment("21/1/2018", 'D/M/YYYY'),
moment("28/1/2018", 'D/M/YYYY'),
moment("4/2/2018", 'D/M/YYYY')
];
var tomorrow = moment().add(1, 'd').startOf('d');
var daysDisabled = [3]; //e.g. disable all wednesday
var selectDate = moment().add(1, 'week').day(2); // e.g. select next tuesday
$("#form_dateTakeout").datetimepicker({
inline: true,
format: 'L',
daysOfWeekDisabled: daysDisabled,
disabledDates: sundaysDisabled,
defaultDate: selectDate,
minDate: tomorrow
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<div class="form-group">
<div class="row">
<div class="col-md-8">
<div id="form_dateTakeout"></div>
</div>
</div>
</div>
The problem is in moment() function usage.
Pay attention:
moment("17/12/2017").isValid() --> returns false
moment("12/17/2017").isValid() --> returns true
Alternatively you can use this format:
moment("17/12/2017", "DD/MM/YYYY").isValid() --> returns true
Check here: https://momentjs.com/
Verify on this working CodePen: https://codepen.io/beaver71/pen/PEqYMv

pickadate.js set focus depending on first input

I am using pickadate.js for arrival & departure dates and would like the departure date to disallow any date on or before the arrival date and set the departure date to focus on the date after the arrival date. Thus an arrival on, say, 16th December 2016 would permit a departure date only from 17th Dec to be selected. This is what I have:
<script src="pickadate/lib/jquery.js"></script>
<script src="pickadate/lib/picker.js"></script>
<script src="pickadate/lib/picker.date.js"></script>
<script src="pickadate/lib/legacy.js"></script>
<script type="text/javascript">
$('#dateArrival').pickadate({
min: true,
max: new Date(2018,12,31),
format: 'd mmm yyyy', // Friendly format displayed to user
formatSubmit: 'yyyy-mm-dd', // Actual format used by application
hiddenName: true, // Allows two different formats
disable: [ // Dates already booked
new Date(2016,11,13),
new Date(2016,11,29)
]
});
$('#dateDepart').pickadate({
min: true,
max: new Date(2018,12,31),
format: 'd mmm yyyy',
formatSubmit: 'yyyy-mm-dd',
hiddenName: true,
disable: [
new Date(2016,11,13),
new Date(2016,11,29)
]
});
</script>
var frompic = $('#input_from').pickadate();
var topic = $('#input_to').pickadate();
After initialization , retrieve picker objects
fromIns = frompic.pickadate('picker');
toIns = topic.pickadate('picker');
Add set event handler
fromIns.on('set', function(event) {
if ( event.select ) {
sel = fromIns.get('select'); //get entered date
newDte = new Date( sel.year,sel.month,sel.date ) ;
newDte.setDate(newDte.getDate()+1); // inc date by 1
toIns.set('min', new Date( newDte.getFullYear(),newDte.getMonth(),newDte.getDate()));
}
});

Razor Syntax Date Picker sends null vlaue to Model if jquery/bootstrap/Kendo ui used

I've a simple date picker which works fine if I do not use any of the Jquery Bootstrap and KendoUI DatePickers but that works only in Chrome. Every time I use other datepickers it just send model null value or one should say 1/01/00001
Here is my razor syntax
<div class="form-group">
#Html.LabelFor(m => m.ModelManpowerRequest.RequestDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModelManpowerRequest.RequestDate, "{0:d}",
new
{
#Value = DateTime.Now,
htmlAttributes =
new { #class = "form-control datepicker date datecontrol" }
})
</div>
</div>
and here is my model
[Display(Name = "Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime? RequestDate { get; set; }
and here is javascript
if ($.browser.mozilla) {
if ($('.datepicker')[0].type != 'date') $('.datepicker').datepicker();
$(function () {
$(".datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange: "1900:2015",
dateFormat: "yy-mm-dd",
defaultDate: '1900-01-01'
});
});
}
and here is another javascript
$(document).ready(function () {
// create DatePicker from input HTML element
$(".datepicker").kendoDatePicker();
});
Well it looks like you are using too much of js libraries specially if you are using kendo and Jquery very much together than I believe you are using the reference of JQuery more than once. Please check your js Bundles and Kendo UI bundles and see the Jquery reference if added than how many time. As of my knowledge MVC KendoUI also adds a Kendo Jquery reference.
Update
for the new error please use this
$('.datepicker').datepicker({
dateFormat: 'dd-mm-yy'
}).datepicker("setDate", new Date());
This will set the date format for you
Update 2
now please change your razor to this
#Html.TextBoxFor(model => model.RequestDate, new { type = "text", #class = "form-control datepicker" })
now what I've done in this one is,I've used type = "text" because by doing that Chrome will not take its type as date and will not render it according to its own behavior now this will work as it has too

Change date field value while submitting the form in django

I have a form
forms.py
class RegistrationForm(BaseRegistrationForm):
name = forms.CharField(label='Name of the Entrepreneur', max_length=120)
ename = forms.CharField(label='Name of the Enterprise', max_length=120)
sector = forms.CharField(label='Industry Sector', max_length=50, widget=forms.Select(choices=zip(SECTOR_CHOICES, SECTOR_CHOICES)))
subsector = forms.CharField(label='Sub-sector', max_length=50, widget=forms.Select(choices=zip(SUBSECTOR_CHOICES, SUBSECTOR_CHOICES)))
address1 = forms.CharField(label='Address Line 1', max_length=100)
address2 = forms.CharField(label='Address Line 2', max_length=100, required=False)
city = forms.CharField(label='City/Town', max_length=50)
state = forms.CharField(label='State', max_length=50)
country = forms.CharField(label='Country', max_length=50)
postal_code = forms.CharField(label='Pin Code', max_length=10, required=False)
estd = forms.DateField(label='Establishment Details')
contact = forms.IntegerField(label='Contact Number')
For the DateField variable I have written javascript
JavaScript Code:
<script type="text/javascript">
$(function() {
$('#id_estd').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'mm/yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
In the estd field it shows mm/yy (ex: 02/2014)
While submitting the form I should submit the value like mm/dd/yy. So How can I change the value while submitting the form??
No use with the javascript or something else. There is a snippet in django use it.
https://djangosnippets.org/snippets/1688/
Save the snippet code in some file called widgets.py and import the class name in your forms.py file and follow the below code:
import datetime
class myForm(forms.Form):
# ...
date = forms.DateField(
required=False,
widget=MonthYearWidget(years=xrange(1990,datetime.date.today().year+1))
)
Hope it works.
It is a better idea to use one format for humans, and another alternate one for processing. JQuery UI Datepicker allows an alternate field to be populated with a different format: http://jqueryui.com/datepicker/#alt-field
Basically rename your existing datepicker field, add a hidden input named estd with an id id_estd (default name and id Django would assign) and add the following lines while initializing your datepicker:
altField: "#id_estd",
altFormat: "mm/dd/yy"
Why use javascript to change the value? Just set the format in django.
class MyForm(Form):
# the default format is %Y-%m-%d
estd = forms.DateField(
widget=forms.widgets.DateInput(format="%m/%Y")
)
Docs for the DateInput widget; https://docs.djangoproject.com/en/1.7/ref/forms/widgets/#dateinput
Date/Time input format settings are detailed here; https://docs.djangoproject.com/en/1.7/ref/settings/#date-input-formats

Categories