Bootstrap Datepicker With Daterange Not Saving Value as the Specified Format - javascript

I have a booking form that requires two dates, so I'm using the built in option that Bootstrap datepicker has (it consists on calling the datepicker function on the father element that contains the inputs), to show the daterange selected, this is my HTML:
<div class="grupo vip-fechas input-daterange">
<div class="barra verde"> <span>¿Cuándo llegas?</span></div>
<input type="text" class="input calendario" id="entrada_input" name="entrada_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_inicio" name="fecha_inicio">
<div class="barra verde"> <span>¿Cuándo te vas?</span></div>
<input type="text" class="input calendario" id="salida_input" name="salida_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_fin" name="fecha_fin">
</div>
This is my Javascript code:
$(document).ready(function(){
iniciarFechas();
});
function iniciarFechas(){
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var date_hidden;
$('.vip-fechas.input-daterange').datepicker({
weekStart: 1,
maxViewMode: 1,
language: "es",
startDate: today,
disableTouchKeyboard: true,
format: {
toDisplay: function(date, format, language) {
var fecha = moment(date).add(1,"day");
date_hidden = fecha;
return fecha.format("dddd DD [de] MMMM, YYYY");
},
toValue: function(date, format, language) {
var fecha = moment(date).add(1,"day");
return moment(fecha).format("DD/MM/YY");
//return moment(date, ["DD.MM.YYYY", "DDMMYYYY"]).toDate();
}
},
}).on("changeDate", function(e){
var fecha_formateada = moment(date_hidden).format("DD/MM/YY");
$(this).next().val(fecha_formateada);
});
}
The daterange works correctly but I want to store the formatted date inside the hidden inputs, as you can see, the format that I want is this: ...format("DD/MM/YY"); but what I get is the display format: format("dddd DD [de] MMMM, YYYY"), also I noticed that $(this) value within this line: $(this).next().val(fecha_formateada); refers to the container div, and not the input that has changed value, so how can I save the date as I want inside the hidden inputs?

I'm not sure what your problem is but by looking at your code I can only guess that you might be in the middle of a race condition.
You're setting the date_hidden variable in Datepicker.toDisplay and then reading from it in the changeDate custom event.
Put a debugger or a console log in both callbacks to make sure you're not in the middle of a race condition.
As for setting the formatted value in the input fields, well I can see in your HTML code that you have selectors that you can use, like the hidden field's ID for example.
Another thing I'd suggest is, instead of setting and reading the date_hidden field in those different callbacks, just call $('#elementID').datepicker('getDate') in the changeDate event handler and do all the transformations you need there, then extract that code and put it in a separate function.

Related

Getting the correct format of the datepicker

I have a column inside of my datebase that stores a date that user pick when they offer a job. It's currently formed in this way: "Fri Feb 15 2019".
I want to be able to compare it to the current date which is formed as: "2019-01-27"
I'm guessing that the best way to do this would be to transform the datepicker format to the date one, and then compare them. This is the code that I have for the date picker currently when someone registeres.
<div class="form-group">
<label for="location" class="control-label">DATE</label>
<input type="text" id="datepicker" class="form-control" placeholder="Pick a
date" name="datepicker">
</div>
<script>
var picker = new Pikaday({ field: document.getElementById('datepicker') });
</script>
Open the example in full page :
Use new Date and then you can extract the day the month and the year
and to compare with another date, you can just new Date("2006-05-1").getMonth() === new Date("2006-05-2").getMonth() && ...
var picker = new Pikaday({
field: document.getElementById('datepicker')
});
const dateInput = document.getElementById('datepicker');
function handleChange() {
const date = new Date(dateInput.value),
formattedDate = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`;
console.log(formattedDate)
}
dateInput.addEventListener("change", handleChange);
<script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css">
<input type="text" id="datepicker">
I would suggest using the javascript plugin called Momentjs. It allows for easy formatting of dates, without the base javascript hassle.
Add this to your HTML, near the bottom of your page, but before your script tags:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Then to format your datepicker value, inside your script, use:
var myDate = moment(picker.value).format('YYYY-MM-DD');
Here is the Momentjs documentation:
Momentjs Docs

How to set selected date on Jquery Calendar Plugin

So I am using the calendar app on a page that has a set date. I have it so when you click on the calendar, whatever is in the input that has the date, gets changed to the date you clicked on.
When you load into the page I want whatever date that is in the input to be what the calendar is set to. Thanks.
LINK TO PLUGIN - https://www.jqueryscript.net/time-clock/Simple-jQuery-Calendar-Date-Picker-Plugin-DCalendar.html
var pageDate = "4/04/2018";
<input class="date">
$('.date').val(pageDate);
// Make above date the selected date
// Code below is for setting input to date you select. Currently works.
$('.box').dcalendarpicker({
format: 'mm-dd-yyyy'
}).on('datechanged', function(e) {
console.log('Date change');
var d = e.date;
selectedDate = moment(d, 'MM-DD-YYYY');
var theDate = selectedDate._i;
$('.date').val(theDate);
var weekdayLongform = selectedDate.format("dddd, MMMM");
var dateLongform = selectedDate.format(" D");
var yearLongform = selectedDate.format(" YYYY");
});
Just set the date as the value of the input (in the same format specified in the plugin initialization). That will do the trick.
<!-- value specifid as mm-dd-yyyy -->
<input class="date" value="03-11-2018">

how do I format date when using pikaday

I am using pikaday module for datepicker, but the format comes as inappropriate format. I tried adding this line of code but still not working:
.config(['pikadayConfigProvider', function (pikaday) {
pikaday.setConfig({
numberOfMonths: 1,
format: "YYYY/MM/DD"
});
}])
This is how my html looks like:
<div class="modal-body">
<form role="form">
<div class="form-group">
<input type="text" class="form-control" pikaday="myPickerObject" name="time" ng-model="clas.class_.time" placeholder="Enter time" tabindex="3">
</div>
</form>
</div>
Also tried to add as an inline attribute
format = "yyyy/mm/dd"
still not working.
Any help
You can use moment.js and set the format by setting
defaultDate : moment().format("MMM YYYY")
this will be the initial input date display format.
For displaying/processing the date in other desired formats, use
var field = document.getElementById('datepicker');
var picker = new Pikaday({
onSelect: function(date) {
field.value = this.getMoment().format('Do MMMM YYYY');
}
});
use moment.js to set the date format:
var picker = new Pikaday(
{
field: document.getElementById('eDate'),
toString(date, format) { // using moment
return moment(date).format('MM/DD/YYYY');
},
});
quick update, if you don't want to use moment.js, you can fdo the following
new Pikaday({
field: document.getElementById('eDate'),
toString: function(date) {
var parts = [('0'+date.getDate()).slice(-2), ('0'+(date.getMonth()+1)).slice(-2), date.getFullYear()];
return parts.join("-");
}
})
this will produce 18-07-1980. You can change from '-' to '/' by changing return parts.join("-"); and you can rearrange parts to apply mm/dd/yyyy via parts array

Javascript - loop through datepickers and set date

I don't know Javascript at all. I have a form where there can be any number of datepicker textboxes. When the user selects a date in the first datepicker textbox, then I want all the remaining datepicker textboxes to have that same date.
Does this require a function?
Edit: I tried to create a function, but I don't know javascript at all!
function UpdateValuationDates(event) {
$valuationDatePicker = $(event.target);
var valuationDate = $valuationDatePicker.datepicker("getDate");
if (valuationDate != null) {
//loop through all items
document.getElementById("dateValuationDate").Text
$valuationDatePicker.datepicker("setDate", valuationDate);
$valuationDatePicker.trigger('change');
}
}
So I think this can be ignored. I have also read that there is a datepicker on selected event:
$(".date").datepicker({
onSelect: function(dateText) {
display("Selected date: " + dateText + "; input's current value: " + this.value);
}
});
So I guess I need to edit this code to populate the rest of the textboxes, but how to find out at runtime how many there are?
The HMTL has a repeater with the datepicker repeated x number of times:
<abc:DatePicker runat="server" ID="dateValuationDate"
With the help of html's input type=date and some basic classes' knowledge, you can do that.. Considering you have following Date pickers:
<input type="date" class="dateTime">
<input type="date" class="dateTime">
<input type="date" class="dateTime">
Now you simply need to listen to a change in any one of there values:
$(".dateTime").on("change", function(){
and when the change occurs, get the changed value and set all other date pickers to that new value:
$(".dateTime").val($(this).val());
So it'll be something like this:
$(document).ready(function(){
$(".dateTime").on("change", function(){
$(".dateTime").val($(this).val());
});
});
See the DEMO here
EDIT: Considering you're new to JavaScript, here's how i'm getting the reference to all those elements, through .className, as they all have same class name so for each event (change, update value) they all will be referenced.

Bootstrap Datepicker attributes not being set

I am trying to set the startDate for my datepicker along with autoclose:true. However, it doesn't work.
Can you please point to what I am doing wrong? I have the code up on jsfiddle at http://jsfiddle.net/alagappanr/9Xek7/
Effective Date: <input type=text size=10 id=effectivedate maxlength=10 name=efdate><br/>
Expiration Date: <input type=text size=10 maxlength=10 name=exdate id=expirationdate>
The JavaScript that I have written for the datepicker is as follows:
jQuery(function() {
var efDP = jQuery("#effectivedate");
var exDP = jQuery("#expirationdate");
efDP.datepicker("setDate", new Date());
efDP.datepicker("update");
exDP.datepicker("setDate", new Date(Date.now()+259200000));
exDP.datepicker("update");
exDP.datepicker({autoclose:true});
efDP.datepicker({
startDate: new Date(),
autoclose:true,
});
efDP.on("changeDate", function(ev){
var effectDate = new Date(jQuery("#effectivedate").val());
jQuery("#expirationdate").datepicker("setDate", new Date(effectDate.getTime()+259200000));
jQuery("#expirationdate").datepicker("update");
});
});
You are trying to update a non-existing datepicker on the first few lines. exDP.datepicker({autoclose:true}); creates a new instance. You have to set the options directly:
jQuery(function() {
var efDP = jQuery("#effectivedate").datepicker({autoclose:true});
var exDP = jQuery("#expirationdate").datepicker({autoclose:true});
efDP.datepicker('setDate', new Date()).datepicker('update');
exDP.datepicker("setDate", new Date(Date.now()+259200000)).datepicker('update');
efDP.on("changeDate", function(e){
exDP.datepicker("setDate", new Date(e.date.getTime() +259200000)).datepicker('update');
});
});
http://jsfiddle.net/svierkant/9Xek7/7/
Please take a look at the documentation, to see if you can reuse objects from events. On the first line of your .on function, your are getting a string from an object (.val()) and making a Date object from it again. The changeDate event however, returns a Date object (which can be reused). Easier coding, more readable and maintainable code.
You should use below coding style.
var efDP = jQuery("#effectivedate");
efDP.datepicker({
startDate: new Date(),
autoclose:true,
});
efDP.datepicker("update", new Date(Date.now()+259200000));

Categories

Resources