How can I check the <input type="date"> to verify if it exceeds today's date or not before submitting ?
The form will not submit if future date is in the input,
<html>
<head>
</head>
<body>
<form>
<ul>
<li>
<label>Member Since </label>
<input id="since" name="since" size="2" maxlength="6" value="" type="date" required />
</li>
<li>
<input type="Submit" name="Submit" id="btnsubmit" value="Submit" onclick="checkDate();" />
</li>
</ul>
</form>
</body>
</html>
Try converting the input value to a Date Object to compare today and the input value in your script.
input = document.getElementById("since"); // gets element
value = input.value; // form value (string)
date = new Date(value); // converts string to date object
now = new Date(); // current date
if (now > date) {
// in past
} else {
// in future
}
You need to check two things. 1) was a valid date entered, 2) is the date in the range you want it. try the code bellow, it will check for both conditions before allowing a submit.
<html>
<head></head>
<body>
<script>
function checkDate() {
var val = new Date(document.forms["frm"]["since"].value);
var now = new Date();
if (isNaN(val.getTime()) || (val>now)) {
alert('invalid date');
return false;
}
return true;
}
</script>
<form name="frm" onsubmit="return checkDate()">
<ul>
<li>
<label>Member Since </label>
<input id = "since" name="since" size="2" maxlength="6" value="" type="date" required/>
</li>
<li>
<input type="Submit" name="Submit" id="btnsubmit" value="Submit" />
</li>
</ul>
</form>
</body>
</html>
Something like that should help you.
var dateText = document.getElementById('since').value;
var date = new Date(dateText);
var now = new Date();
if (date > now) {
console.log("Date needs to be in the past");
}
Related
I'm trying to collect 2 dates using input boxes ids From and To. I would like to subtract 1 day from the date value received using "FROM" text box and pass that new value to the button click event.
The code below works to push values received from the input box. However, i wish to subtract 1 day and pass on the same.
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
From : <input type="date" class="form-control" id="From" placeholder="From" aria-label="From">
To : <input type="date" class="form-control" id="To" placeholder="To" aria-label="To">
<input type="button" onclick="location.href='#SITE#/TDL-Test-code.aspx?FromTo=(Date ge datetime%27'+FD+'T00:00:00.000Z%27) and (Date le datetime%27'+ document.getElementById('To').value+'T23:59:00.000Z%27)';" value="Submit" />
Edit:
Following is my moment JS function
var oldfrom = document.getElementById('From').value;
newdate = moment(oldfrom).subtract(1, 'days').format("YYYY-MM-DD");
var FD = newdate;
Issue was fixed with solution below.
document.getElementById("From_Local").oninput = function() {
var dateLocal = document.getElementById("From_Local").value;
var dateUTC = moment.utc(dateLocal).subtract(4, 'hours').format("YYYY-MM-DD");
document.getElementById("From_UTC").value = dateUTC;
}
From:<input name="From" required type="date" id="From_Local">
<input type="hidden" id="From_UTC">
To:<input name="To" required type="date" id="To">
<input type="button" onclick="location.href='SITE_URL?FromTo=(Date%20ge%20datetime%27'+ document.getElementById('From_UTC').value+'T00:00:00.000Z%27)%20and%20(Date%20le%20datetime%27'+ document.getElementById('To').value+'T00:00:00.000Z%27)';" value="Submit" />
I have form like below:
<div id="form">
<form>
First Name: <input type="text" name="firstname" id="firstname">
Last Name: <input type="text" name="lastname">
Start Time: <input type="hidden" name="starttime" id="starttime">
<input type="submit" value="Submit">
</form>
</div>
I want to store a timestamp in a local storage when data is entered for the first time in firstname input. When the form is submitted, I will insert that timestamp as Start Time and form submit time as End Time in database.
Here is what I have so far:
<script>
$(document).ready(function(){
var startTime = '';
$('#firstname').change(function (){
if (startTime) == ''
{
var timeStamp = new Date();
sessionStorage.setItem("startTime",timeStamp);
}
});
});
</script>
Now, how do I send the startTime value from javascript to the starttime html input? Any help will be much appreciated.
You can use step attribute in your input tag:
<input type="time" name="timestamp" step="1">
W3C: input: type=time
I am relative new in coding and recently i have to do some date manipulations with data entered in a form. I searched a lot and I haven't found the solution that works for me.
Here is the issue:
The user enters following data in datetime-local fields in HTML:
1) Year of entering College (date 1)
2) Year of graduation (date 2)
3) Birthday (date 3)
I need a JQuery or a JavaScript script that uses this dates and output following:
1) Year of admitting, based on the admittion date (I know there is a getFullYear function, but I couldn't use it right...) >>> result1
2) Age at graduation (date difference between Birthdate and date of Graduation. >>> result2
I tried with adding datepicker but somehow I got really awful looking calendar which was displayed over the boxes. I couldn't install datetimepicker...
Thank you in advance. Your help is appreciated.
Here is my HTML code.
<input id="date1" type="datetime-local"/>
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="text" readonly="true" name="year" placeholder="=(getFullYear from date1)"/>
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)"/></textarea>
<label for="result2">age</label>
<br />
You didn't include the js code which is more important for this question. I'll include a couple functions that should help.
To find a year from a date, I use the following function
function getYearFromDate(date){
const yearFromDate = new Date();
yearFromDate.setTime(date.getTime());
yearFromDate.setFullYear(date.getFullYear() + 1);
return yearFromDate;
}
console.log(getYearFromDate(new Date()));
And the graduation age copied mostly from Calculate age given the birth date in the format YYYYMMDD
function getYearsBetween(oldDate, newDate) {
var age = newDate.getFullYear() - oldDate.getFullYear();
var m = newDate.getMonth() - oldDate.getMonth();
if (m < 0 || (m === 0 && newDate.getDate() < oldDate.getDate())) {
age--;
}
return age;
}
Including moment.js is also an option, but it's a large library I like to avoid if I can.
EDIT I thought you wanted year + 1 day. Getting the full year from the date is even easier.
const date = new Date();
console.log(date.getFullYear());
Edit: All together now
function updateGradYear(event) {
console.log(event.target.value);
let date = new Date(event.target.value);
document.querySelector('#result1').value = date.getFullYear();
}
function updateAge() {
let gradDate = new Date(document.querySelector('#date2').value);
console.log(document.querySelector('#date3').value);
let birthdate = new Date(document.querySelector('#date3').value);
document.querySelector('#result2').value = gradDate.getFullYear() - birthdate.getFullYear();
}
// set some default values
let today = new Date();
document.querySelector('#date1').value = today.toISOString().split('.')[0];
document.querySelector('#result1').value = today.getFullYear();
document.querySelector('#date2').value = today.toISOString().split('.')[0];
let birthdate = new Date(today.getTime);
birthdate.setFullYear(1984);
console.log(birthdate.toISOString().slice(0, 10).replace(/\//g, "-"));
document.querySelector('#date3').value = birthdate.toISOString().slice(0, 10).replace(/\//g, "-");
updateAge();
<input id="date1" type="datetime-local" onchange="updateGradYear(event)" />
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="number" readonly="true" name="year" placeholder="=(getFullYear from date1)" />
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" onchange="updateAge()" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" onchange="updateAge()" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)" /></textarea>
<label for="result2">age</label>
<br />
Let me know how this works for you! And as i said please enter all the fields while running this code!
$('#date1, #date2').on('blur',function(){
var dc = document.querySelector('input[id="date1"]');
var date = new Date(dc.value);
var collegeadmission = date.getFullYear();
$('#result1').val(date.getFullYear());
dc = document.querySelector('input[id="date2"]');
date = new Date(dc.value);
var collegegrad = date.getFullYear();
if(! isNaN(collegegrad))
$('#result2').val(collegegrad - collegeadmission);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="date1" type="datetime-local"/>
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="text" readonly="true" name="year" placeholder="=(getFullYear from date1)"/>
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)"/></textarea>
<label for="result2">age</label>
<br />
check out this url:http://jsbin.com/vebiwogipu/edit?html,js,output
Make sure u fill all the dates and time properly as you discussed in your html.
Similarly you can attach the output on click or change event.
and aso you can leverage getMonth() and getDay() in the code to get desired output.
Take a look at the label and may be alert, when you click the button, it shows year out of your first date field. As i said you need to add the logic for rest.
let me know if it makes sense, if not please add more information to make me understand!
I have x number of textboxes with same class name. I want the user to enter dates in them and each date should be greater than the previous one. How can I achieve this?
jQuery -
jQuery.validator.addMethod("greaterrule", function(value, element, param) {
return $(param).not(element).get().every(function(item) {
return $(item).val() < value;
});
}, "Please specify a greater value");
jQuery.validator.addClassRules("dept_date", {
greaterrule: ".dept_date"
});
HTML -
First Date <input type="text" name="first_date" class="dept_date"> <br>
Second Date <input type="text" name="second_date" class="dept_date"> <br>
Third Date <input type="text" name="third_date" class="dept_date"> <br>
Fourth Date <input type="text" name="fourth_date" class="dept_date"> <br>
Try using prevAll to check against all the dates before and use Date to compare:-
jQuery.validator.addMethod("greaterrule", function(value, element, param) {
return $(element).prevAll(param).get().every(function(prev) {
return new Date($(prev).val()) < new Date($(element).val());
});
}, "Please specify a greater value");
jQuery.validator.addClassRules("dept_date", {
greaterrule: ".dept_date"
});
$("form").validate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<form method="post">
First Date
<input type="text" value="01/21/2016" name="first_date" class="dept_date">
<br>Second Date
<input type="text" value="01/22/2016" name="second_date" class="dept_date">
<br>Third Date
<input type="text" value="01/23/2016" name="third_date" class="dept_date">
<br>Fourth Date
<input type="text" value="01/24/2016" name="fourth_date" class="dept_date">
<br>
<input type="submit" value="submit" />
</form>
I have this piece of code, and I'm trying to assign a value to variable days (if one of the combinations of checkbox checked are true), and send by submit to another asp.
The problem is that the variable doesn't take any value. Here's the code:
<html>
<head>
<script type="text/javascript">
function validatedays(days) {
var dias=3
if(document.getElementById("chkmonday").checked && document.getElementById("chktuesday").checked)
{ var days=1;}
if(document.getElementById("chkwednesday").checked && document.getElementById("chkthursday").checked)
{ var days=2;}
if(document.getElementById("chkfriday").checked) {
var days=3 }
datos.submit()
}
</script>
</head>
<body>
<form method="post" id="data" name="data" action="blabla.asp">
<input type="text" name="txtsurname" id="txtsurname" size="20" /><br />
<input type="text" name="txtcuota" id="txtcuota" size="20" /><br />
<br />
<input type="checkbox" value="chklunes" name="chkmonday" /><br/>
<input type="checkbox" value="chkmartes" name="chktuesday" /><br/>
<input type="checkbox" value="chkmiercoles" name="chkwednesday" /><br/>
<input type="checkbox" value="chkjueves" name="chkthursday" /><br/>
<input type="checkbox" value="chkviernes" name="chkfriday" /><br/>
<br/>
<input type="submit" value="Calcular" onclick="javascript:validatedays(days)" />
<input type="reset" value="Clean" />
</form>
</body>
</html>
The var keyword declares a variable in the current scope. You need to declare days in the scope of your whole function. Then you need a way to pass your value in the form: this is usually done with a input type="hidden".
function validatedays() {
var days;
if(document.getElementById("chkmonday").checked && document.getElementById("chktuesday").checked) {
days=1;
} else if(document.getElementById("chkwednesday").checked && document.getElementById("chkthursday").checked) {
days=2;
} else if(document.getElementById("chkfriday").checked) {
days=3;
}
// Assign days to the value of a (hidden) input in the form
document.getElementById('data').submit();
}
Your button being a type="submit", I think you don't need the last line (unless you cancel the event).
The problem is that when you do var <name of the variable> you are redeclaring it when you don't have to. So remove the var keyword.
Also, you were missing some ; and most importantly, you hadn't defined datos (which, I guess was supposed to be the form).
var datos = document.getElementById('data');
function validatedays(days) {
if (document.getElementById('chkmonday').checked
&& document.getElementById('chktuesday').checked) {
days = 1;
}
if (document.getElementById("chkwednesday").checked
&& document.getElementById("chkthursday").checked) {
days = 2;
}
if (document.getElementById("chkfriday").checked) {
days = 3;
}
datos.submit();
}