How to make a datepicker the minimum day in javascript - javascript

I want that the user can't choose previous dates, I'm using the .min function but it doesn't do anything. If you could help me.
function deshabilitarFechasAnterior(){
const inputFecha=document.querySelector('#fecha');
const fechaAhora= new Date();
const year=fechaAhora.getFullYear();
const mes=fechaAhora.getMonth()+1;
const dia=fechaAhora.getDate()+ 1;
const fechaDeshabilitar=`${year}-${mes}-${dia}`;
inputFecha.min=fechaDeshabilitar;
}

The format for min (and max) is yyyy-mm-dd ... since May is a single digit (5), the min is being ignored
you want min to be 2022-05-11 not 2022-5-11
Simplest fix to your code is by using toString and padStart for both month and day component
Note, added one day (like your code does) BEFORE getting year/month/day ... since your way of doing it would fail on the last day of the month for obvious reasons - since there is no 32nd of May for example!!
Of course, if "min" date is supposed to be today, simply DONT include that one line of code - your code implies it should be tomorrow (albeit done incorrectly) but your question states "previous dates", which implies TODAY is a valid choice - so, you must decide if that one line is included or not, since your question implies BOTH
function deshabilitarFechasAnterior() {
const inputFecha = document.querySelector('#fecha');
const fechaAhora = new Date();
// the next line makes the minimum date TOMORROW
fechaAhora.setDate(fechaAhora.getDate() + 1);
const year = fechaAhora.getFullYear();
const mes = (fechaAhora.getMonth() + 1).toString().padStart(2, '0');
const dia = (fechaAhora.getDate()).toString().padStart(2, '0');
const fechaDeshabilitar = `${year}-${mes}-${dia}`;
inputFecha.min = fechaDeshabilitar;
}
deshabilitarFechasAnterior();
<input type="date" id="fecha" />
Alternative - this is how I would go about it
Take advantage of the fact that fr-CA date string is yyyy-mm-dd
function deshabilitarFechasAnterior() {
const inputFecha = document.querySelector('#fecha');
const fechaAhora = new Date();
// the next line makes the minimum date TOMORROW
fechaAhora.setDate(fechaAhora.getDate() + 1);
inputFecha.min = fechaAhora.toLocaleDateString('fr-CA');
}
deshabilitarFechasAnterior();
<input type="date" id="fecha" />

Simply do:
const inputFecha = document.querySelector('#fecha')
deshabilitarFechasAnterior();
function deshabilitarFechasAnterior()
{
let dateMin = new Date()
dateMin.setMinutes(dateMin.getMinutes() - dateMin.getTimezoneOffset())
inputFecha.value = // to set default value too...
inputFecha.min = dateMin.toISOString().split('T')[0]
}
<input type="date" id="fecha" />
If you don't want to code anything with the time zone offset,
the Html5 do it for you:
const inputFecha = document.querySelector('#fecha')
deshabilitarFechasAnterior();
function deshabilitarFechasAnterior()
{
inputFecha.valueAsDate = new Date()
inputFecha.min = inputFecha.value
}
<input type="date" id="fecha" />

Using Javascript
function deshabilitarFechasAnterior() {
const inputFecha = document.querySelector('#fecha');
// To set a custom date as a minimum date, create date object for that date
// const fechaAhora = new Date("2022-05-11");
const fechaAhora = new Date(); // Default today's date
const year = fechaAhora.getFullYear();
const mes = (fechaAhora.getMonth() + 1).toString().padStart(2, '0');
const dia = (fechaAhora.getDate()).toString().padStart(2, '0');
const fechaDeshabilitar = `${year}-${mes}-${dia}`;
inputFecha.setAttribute("min", fechaDeshabilitar);
}
deshabilitarFechasAnterior();
<input type="date" id="fecha" />
Using HTML by adding min/max attributes.
<input id="fecha" type="date" min="2022-05-10" max="2022-05-25" />

Related

How can I make html input type date automatically update the range

How can I make this code automatically update the range. the minimum should always not less than 18 years and max not more than 70yrs on the day a client fill up this form is their html trick for this?
<input type="date" name="birthdate" id="birthdate" min="" max="">
if you would like be automatically for a long terms you should use js
(()=>{
const birthdate = document.getElementById("birthdate");
const min = new Date();
const max = new Date();
min.setFullYear( min.getFullYear() - 18)
max.setFullYear( max.getFullYear() + 70)
console.log(min, max)
birthdate.setAttribute("min", ''+min.getFullYear());
birthdate.setAttribute("max", ''+max.getFullYear());
})()

Only enable during 2 weeks date format html

I have a problem enabling only during 2 weeks data format. For example, I want only to show today and before 14 days. Now my coding just can lock before days.
Scenario:
If today 03 Feb 2021, I want to enable dates are 20 Jan 2021 until 03 Feb 2021. Other dates will be disabled.
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("accident")[0].setAttribute('min', today);
<input type="date" class="form-control" id="accident" name="accident" value="" title="Date of Accident">
Now my result like below the picture:
Hope someone can guide me on which part I am getting wrong it. Thanks.
According to MDN Documentation. You need to set min and max values to specify an interval
// Get date objects
const today = new Date();
const twoWeeksAgo = new Date();
twoWeeksAgo.setDate(today.getDate() - 14);
// Then set in input
const input = document.querySelector('[name=accident]');
input.setAttribute('min', twoWeeksAgo.toISOString().slice(0, 10));
input.setAttribute('max', today.toISOString().slice(0, 10));
<input type="date" name="accident" />
You only set min, but you did not set max.
Because of this relationship, it only knows your minimum date, but does not know your maximum date, so the previous result is normal, as long as you make up the setting, it will work.
For details, please refer to here.
const getDateStr = (d) => d.toISOString().split('T')[0];
const daysRange = (days) => {
const d = new Date();
const when = new Date(d.setDate(d.getDate() + days));
return [new Date(), when].map(m=>getDateStr(m));
};
const limit = daysRange(-14);
const picker = document.getElementsByName("accident")[0];
picker.setAttribute('min', limit[1]);
picker.setAttribute('max', limit[0]);
picker.setAttribute('value', limit[0]);
label {
display: block;
font: 1rem 'Fira Sans', sans-serif;
}
input,
label {
margin: .4rem 0;
}
<label for="start">date:</label>
<input type="date" name="accident">
The solution you're looking for is something like this,
const twoWeeksAgo = 14 * 24 * 60 * 60 * 1000;
let dateElement = document.querySelector('#accident');
dateElement.min = new Date(Date.now() - twoWeeksAgo).toISOString().split('T')[0];
dateElement.max = new Date().toISOString().split('T')[0];
<input type="date" class="form-control" id="accident" name="accident" value="" title="Date of Accident">
You can use the max and min attributes of the HTML5 date element (documented here) to restrict your element to only show certain values.
In this particular case, the min attribute is set to the date (in yyyy-mm-dd format) two weeks ago and the max attribute is set to the current date.
The magic computation twoWeeksAgo is the number of milliseconds in 14 days which will allow you to compute the date 14 days ago.
The code new Date(Date.now() - twoWeeksAgo) gives us a Date object set to two weeks ago and the .toISOString() function returns the date in YYYY-MM-DDTHH:mm:ss.sssZ format, i.e., a date-time string.
Since the min attribute only requires the date and not the time, we then split the obtained string using 'T' as a delimiter, which would give us the date in YYYY-MM-DD format.
Putting it all together we get this line for the date two weeks ago
dateElement.min = new Date(Date.now() - twoWeeksAgo).toISOString().split('T')[0];
And similarly for the upper limit date,
dateElement.max = new Date().toISOString().split('T')[0];

I want to store the value of a datePicker in WixCOde

Based on this Supplied Code,
$w.onReady(function () {
//TODO: write your page related code here...
const startFromDays = 4;
const endAtMonths = 9;
const today = new Date();
let startDate = new Date(today);
let endDate = new Date(today);
startDate.setDate(startDate.getDate() + startFromDays);
endDate.setMonth(endDate.getMonth() + endAtMonths);
$w.onReady(function () {
$w("#datePicker1").minDate = startDate;
$w("#datePicker2").maxDate = endDate;
});
});
I need help to find the difference between the endDate and the startDate and output it as Text. Knowing the fact that some start dates can be of the Eg: 26th of Feb and end Date can fall on 3rd March.
This Code is been run on Wixcode, where the dates are used as a Date-picker user input. Thank you.
Start by getting the difference between the two dates using something like what is described in this post.
Then, use that number to populate a text field that you've added to your page.
So, assuming you have a datediff() function declared:
const diff = datediff(startDate, endDate);
$w("#text1").text = diff.toString();

Need to compare new date with datepicker

Im struggling with dates in javascript. Im going to compare some dates input but the user and the date the user input depends which list the information goes. My issue is comparing the system date and the date picker date. The system date shows the format of 'Tue Dec 22 2015 00:00:00 GMT+0000 (GMT)' date picker shows 22/12/2015. How can i change the system date to match the date picker format so i can compare dates? I want to do it without jQuery(i know date picker goes against this).
Here my code so far for the date which basically is just setting the time to 00:00:00.
var today = new Date();
today.setHours(0,0,0,0);
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0,0,0,0);
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0,0,0,0);
console.log(today);
var dateTask = document.getElementById("date").value;
console.log(dateTask);
You have to parse the user input into a Date object. 22/12/2015 is not a valid datestring for the Date constructor so you have to parse it yourself.
You can do something like this:
var dateSplit= document.getElementById("date").value.split('/'),
dateTask = new Date(dateSplit[2],dateSplit[1]-1,dateSplit[0], 0, 0, 0, 0);
Note: this code is very basic and needs an enhancement when you're parsing real user input.
After that you can compare the dates like this:
today.getTime() === dateTask.getTime()
Just split the string with str.split("/"); and construct Date in one of the ways that is pointed out here.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date
be careful months are from 0-11
You don't actually need JQuery if you want a date-picker, but that's beside the point. I think the best approach is to parse the user input as a date using Date.parse. You can then compare them as unix epoch timestamps.
"use strict";
var datePicker = document.querySelector('#date');
datePicker.addEventListener('change',function(){
var udate = Date.parse(this.value);
var sysdate = Date.now();
document.querySelector('#d').innerText = udate;
document.querySelector('#sys').innerText = sysdate;
});
form {
position: relative;
}
label, input, output {
float: left;
}
label {
clear: left;
width: 128px;
}
<form>
<label for="date">user input</label>
<input type="date" name="date" id="date">
<label for="d">user date</label>
<output id="d" name="d" for="date"></output>
<label for="sys">system date</label>
<output id="sys" name="sys"></output>
</form>
const datePicker = document.querySelector("#date");
const todayDate = new Date().toLocaleDateString();
const datePickerValue = new Date(datePicker.value).toLocaleDateString();
datePicker.addEventListener("change", () => {
if (datePickerValue === todayDate) {
alert("");
} else {
alert("");
}
});

Populate fields with dates JS/JQ

So I have this line:
<input type="date" id="Date1" name='date' data-role='datebox'
data-options='{"dateFormat": "mm/dd/YYYY"}' />
Works as it should, I'm using this.
When I click on that <input> a datepicker will come up and and the user will be able to choose a date with the mm/dd/yyyy format.
However, I want to populate that field, before, let's say onload, window ready, I don't even care, with the date of today.
I'm trying this:
<script type="text/javascript">
today = new Date();
var dateString = today.format("dd/mm/yyyy");
document.getElementById("Date1").innerHTML = dateString;
</script>
And I basically know where the problem is, I'm trying to add a string into a type="date" field; I've also tried, instead of using .innerHTML, .value but still no luck, Not sure how to do it.
Also, keep in mind that I have 3 more fields that have to be populated.
1: - the one that I've already pasted >> current date 2: - current
date +19 weeks 3: - current date +72 weeks 4: - current date +1 week
I don't mind using JQ if needed.
This works:
document.getElementById('Date1').valueAsDate = new Date();
Refer the API here
Your datepicker seems to be able to do what you want: RFTM darn it. It also seems your are not using a regular date input (inspect your date widget you'll see that it is actually a text input). My guess is that your datepicker transforms the date input in a text input when it's initialized.
I actually fixed it with patience and readng a lot.
Here's the code.
This to populate the fields when you open the document:
<script type="text/javascript">
today = new Date();
var dateString = today.format("dd/mm/yyyy");
document.getElementById("Date1").value = dateString;
var dateString18 = new Date(+new Date + 10886400000);
dateString18 = dateString18.format("dd/mm/yyyy");
document.getElementById("Date2").value = dateString18;
var dateString90 = new Date(+new Date + 54432000000);
dateString90 = dateString90.format("dd/mm/yyyy");
document.getElementById("Date3").value = dateString90;
var dateString1 = new Date(+new Date + 604800000);
dateString1 = dateString1.format("dd/mm/yyyy");
document.getElementById("Date4").value = dateString1;
</script>
And this is to calculate the other fields after I change the first one:
function dateChange(fecha) {
var anyo = fecha.substring(0, 4);
var mes = fecha.substring(5, 7);
var dia = fecha.substring(8, 10);
var fechaFormato = dia + "/" + mes + "/" + anyo;
document.getElementById("Date1").value = fechaFormato;
var strDate = fechaFormato;
var dateParts = strDate.split("/");
var dateBuena = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
var dateString18 = new Date(+dateBuena + 10886400000);
dateString18 = dateString18.format("dd/mm/yyyy");
document.getElementById("Date2").value = dateString18;
var dateString90 = new Date(+dateBuena + 54432000000);
dateString90 = dateString90.format("dd/mm/yyyy");
document.getElementById("Date3").value = dateString90;
var dateString1 = new Date(+dateBuena + 604800000);
dateString1 = dateString1.format("dd/mm/yyyy");
document.getElementById("Date4").value = dateString1;
}

Categories