Bootstrap Datepicker attributes not being set - javascript

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));

Related

Bootstrap Datepicker With Daterange Not Saving Value as the Specified Format

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.

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

WebForm Date Field

I am creating a form and not finding how to populate a date field with the calendar date. The form should populate the date when a new form is created. I have the following code:
<div>
<label><b>Request Initiation Date</b></label><br />
<input type="date" id="RequestDate">
<script>
(function() {
var date = new Date().toISOString().substring(0, 10);
var field = document.querySelector('#Requestate');
field.value = date;
console.log(field.value);
});
</script>
</div>
You have two issues. Firstly, in
document.querySelector('#Requestate')
you have mistyped the element ID, it should be
document.querySelector('#RequestDate')
--------------------------------^
Secondly, you aren't calling the function, so the last line should be:
}());
-----^^
The full code:
<div>
<label><b>Request Initiation Date</b></label><br />
<input type="date" id="RequestDate">
<script>
(function() {
var date = new Date().toISOString().substring(0, 10);
var field = document.querySelector('#RequestDate');
field.value = date;
console.log(field.value);
}());
</script>
</div>
Of course you can write it in less code, but you should consider readability and maintainability before doing that.
You can use the below-given js -
document.getElementById("RequestDate").valueAsDate = new Date()
The new Date() fn will get the current date and assign it to the target input[type=date] control.

get saved value on input flatpickr angular

I have a flatpickr angular component that I use to save a date with Format:
<input ng-flatpickr class="flatpickr" fp-opts="$ctrl.dateOpts" fp-on-setup="$ctrl.dateDebutSetup(fpItem)" ng-model="$ctrl.selected.selectedDateDebut" data-enabletime="true" placeholder="Selectionner Date..">
When I save this date I have no error, I get the ng-model with the
$scope.dateDebutSetup = function (fpItem) {
fpItem.set("onChange", function (selectedDates, dateStr, instance) {
$scope.selected.selectedDateDebut = selectedDates[0];
});
};
and I save it in my db
selection.selectedDateDebut= $filter('date')(new Date($scope.selected.selectedDateDebut), "dd/MM/yyyy HH:mm");
But when I try to get the saved value on my input to modify it, It's doesn't work, the value is not loaded
I tried a lot of examples but I don't find a solution:
$ctrl.selected.selectedDatesDebut = $filter('date')(indispo.dateDebut, "dd/MM/yyyy HH:mm");
this one:
$ctrl.selected.selectedDatesFin = moment(indispo.dateFin).format('DD/MM/YYYY HH:mm');
or Juste with:
$ctrl.selected.selectedDatesFin = new Date (indispo.dateDebut);
Can someone help me please. And thank's in advance :)

How to save Date & Time in Parse.com using Javascript

I am trying to get the Date and Time from the user and want to submit it to Parse.com. But when I am facing the problem with the following code
What mistake am I doing here?
<div id="main">
<form name="myForm" action="" method="get">
Date: <input type="datetime-local" name="datentime" id="theDate">
<input type="submit" value="Submit" onclick="myFunction()">
</form>
and the javascript code
function myFunction()
{
var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
var date = new Date();
date = document.getElementById("theDate").value; //document.forms["myForm"] ["datentime"].value; /*new Date();*/
testObject.set("myDate", date);
testObject.save(null, {
success: function(testObject) {
$(".success").show();
},
error: function(testObject, error) {
$(".error").show();
}
});
}
In above line testObject.set("myDate", date); this like is not working.I am not sure how to take the input from the date and give it to the parse.com
where the column name is myDate of type Date
If I try testObject.set("foo","testing...") where foo is column name of type string.It's working properly
Your issue is just with the way that you are creating a date. I would think that it should work, but is it possible that it is creating a string object?
try checking the type of date it should show an object, if it does not, then the date is not a date, but just a string:
console.log(typeof(date));
Also try to log the value:
console.log(document.getElementById("theDate").value);

Categories

Resources