This is my html code with a snippet of just the code I am trying to use to invalidate/validate date entries with hopefully all of the corresponding and necessary variables declared.
<html>
<head>
<title> Booking Page </title>
<script>
function Booking(){
var departuredate = document.getElementById("departdate").value; //departure date selected by user
var arrivaldate = document.getElementById("arrivedate").value; //arrival date selected by user
departuredate = new Date(departuredate);
arrivaldate = new Date(arrivaldate);
CurrentDate = new Date(); //todays date
month = '' + (arrivaldate.getMonth() + 1),
day = '' + arrivaldate.getDate(),
year = arrivaldate.getFullYear();
var adate = [day, month, year].join('/');
alert(adate);
the adate is for the arrival date only. I plan to just copy and adjust the code across once it is correct for the departure date. Currently the code seems to invalidate all entries, not allowing completely valid entries to be validated.
var re = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
if (!adate.match(re))
{
document.getElementById("temp").innerHTML = "Incorrect format"
document.MyForm.arrivedate.focus();
document.getElementById("arrivedate").style.border='1px solid red';
return false;
}
else
{
// if none of the above situaton's occur then the input is true and validated
alert('Dates are validated');
return true;
}
}
</script>
</head>
<body>
<H1> Booking Form </H1>
<Form action="testpage.py" method="POST" name="MyForm" onsubmit="return Booking()">
<p>Departure Date:</p>
<input type=date name="departdate" id="departdate" >
<p>Arrival Date:</p>
<input type=date name="arrivedate" id="arrivedate">
<input type=submit value="Find flights">
</Form>
</body>
</html>
You have multiple problems here. First is that the date type for inputs is non-standard, so it won't work in most browsers (IIRC chrome, edge, and iOS safari are the exceptions).
I recommend that you either use a third-party library like jquery-ui-datepicker or use a text input with the validation logic using the html pattern attribute or a js event handler if you have to support desktop safari (which doesn't support the pattern attribute).
Something like <input type="text" pattern="/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/"...
Or if pattern won't work:
var myDateInput = document.getElementById('date-input');
myDateInput.addEventListener('change', function(e) {
if (!(e.target.value.match(dateRegex)) {
//let user know somehow
}
});
You can throttle the handler so that it doesn't fire on successive keystrokes. Also note that even in browsers with the date input type they expect "yyyy-mm-dd" format, so make your regex:
/[0-9]{4}-[0-9]{2}-[0-9]{2}/.
Related
Hello I have input on registration form and want to retrieve the value of input and compare it with the current date using JavaScript and display message after check age if age less than 18 year and display custom message on the bottom of input.
var dateControl = document.querySelector('input[type="date"]').getFullYear();
var startDate = new Date(document.getElementById('date1').value);
and this is the HTML
<input type="date" name="date" class="form-control" id="date1" value="{{ old('date', date('Y-m-d')) }} " onclick="checkDate()">
<div id="currentdate"></div>
but is give old value after each click.
and the message not displayed
Best regards
Not much code to go from but I think you may need this function anyway to compare the date you receive from the form with the current date and get the difference
function process() {
var today = new Date();
var date = new Date(document.getElementById("date1").value);
var diff = Number((today.getTime() - date.getTime()) / 31536000000).toFixed(0);
if (diff >= 18) {
// Your form submission goes here
console.log("success");
} else {
// your error handeling goes here
console.log("error");
}
}
PS: That this method won't give you the difference in an exact way,
it will just give you the difference between the years.
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.
I've been using forms which upon submit call a function which makes use of the inputted data. So far this has worked fine with text, but switching to date inputs is causing me trouble.
I'm using the following code, but the "startDate", "endDate" values are empty.
<form onsubmit="myFunction()">
Start Date:
<input type="date" name="startDate" id="startDate">
End Date:
<input type="date" name="endDate" id="endDate">
<input type="submit">
</form>
<!-- Form to process above date submit -->
<script>
function myFunction() {
var locationID = "1";
var startDate = document.getElementById("startDate").value;
var endDate = document.getElementById("endDate").value;
var apiURL = "APIUrl" + locationID + "_" + startDate + "_" + endDate;
alert("The form was submitted" + apiURL);
$.get(apiURL, function( data ) {
$( ".result" ).html( data );
});
}
</script>
The alert gives me back the APIUrl, plus the location ID, but blank values for the dates.
Any ideas?
Thanks for your help.
You didn't specify what browser you are using.
Since you're already using jQuery, I recommend using it to retrieve the field values, i.e.
var startDate = $("#startDate").val();
var endDate = $("#endDate").val();
That would resolve browser inconsistencies that could play a part in your issue.
Your code work as expected in Chrome because it supports input date but this is not the case for IE, Firefox and Safari as you can see here : http://caniuse.com/#search=input%20date
It would probably be better if you use a library like JQuery-UI for the datepicker so it can be supported by all browsers
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);
Trying to create a simple age calculator. At the moment the current year will populate but when you enter your birth year and click submit nothing happens.
function aaa(){
date=new Date();
var y=date.getFullYear();
document.getElementById('ddd').value=y;
}
function display(){
var c=document.getElementById('eee').getFullYear.value;
//var aa= document.getElementById('eee').(this).('getDate').value;
var e= y - c;
{
document.write("Ans="+e);
}
alret(e);
}
<body onload="aaa();">
<form name="xyz" method="post">
CurrentDate:<input type="text" name="ddd" id="ddd">
BirthDate:<input type="date" name="eee" id="eee">
Age:<input type="text" name="age" id="age">
<input type="submit" name="submit" value="submit" onClick="display();">
</form>
</body>
Probably better for code review, but here goes:
<script language="javascript">
The language attribute for script elements was deprecated in HTML 4 and removed in HTML5. Remove it.
function aaa()
Functions should have a meaningful name, e.g. setYear.
{
date=new Date();
You should keep variables local with var.
var y=date.getFullYear();
document.getElementById('ddd').value=y;
You could just do:
document.getElementById('ddd').value = new Date().getFullYear();
}
function display()
{
var c=document.getElementById('eee').getFullYear.value;
Input type date isn't supported by all browsers, and that won't work anyway. If you are just using the difference in years (which will be incorrect by 1 year about half the time) then why not just ask for the year?
var e= y - c;
{
document.write("Ans="+e);
}
The block is redundant, and calling document.write after the load event will first clear the entire document (everything, including all scripts) and load a new document with just the content passed to document.write.
[...]
So a re-write might look like:
function calcAge(element) {
var form = element.form;
form.age.value = form.currentYear.value - form.birthYear.value;
}
window.onload = function() {
document.forms[0].currentYear.value = new Date().getFullYear();
}
<form>
Current year: <input name="currentYear"><br>
Birth year: <input name="birthYear"><br>
<input type="button" onclick="calcAge(this)" value="Caluclate age"><br>
Your age: <input name="age" readonly><br>
</form>
Note that every control in a form has a form property that references the form it's in. Also, form controls with a name are available as named properties of the form (hence a control named submit overwrites the submit method).
document.getElementById('eee') is a DOM element.
document.getElementById('eee').getFullYear is, judging from your code, undefined.
document.getElementById('eee').getFullYear.value should throw an error.
You were trying to read a property from an object which is (unfortunately) undefined, that's why your code doesn't work. Open console and see if there is a red line saying something like this:
Cannot read property 'value' of undefined