WebForm Date Field - javascript

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.

Related

How to add sql query varible into javascript and calculate?

I'm making a patient system with calculating the age of patient base on their birthday, but i'm getting error when I add it
Javascript:
<script>
var dob = new Date("06/24/2008"); <!-- I wanted to add {{ patient.birth }} into the date part-->
//calculate month difference from current date in time
var month_diff = Date.now() - dob.getTime();
//convert the calculated difference in date format
var age_dt = new Date(month_diff);
//extract year from date
var year = age_dt.getUTCFullYear();
//now calculate the age of the user
var age = Math.abs(year - 1970);
//display the calculated age
document.write("Age of the date entered: " + age + " years");
</script>
And {{ patient.birth }} is the sql query that I wanted to add into the script.
var birthdate = $("#birth").val();
or
var birthdate = "{{ birth }}"
Depending on how the value is being implemented in the jinja.
Let me know which one works for you situation if you could.
I've done this in the past using both of these methods.
note: it's not by accident I'm leaving the "patient." out. This is intentional.
If they are changing the birthdate value on this screen.
Then you need to make an onchange event.
For example:
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<style>
function makeChange() {
var birthdate = $("birth").val();
}
</style>
</head>
<form method="POST" action="">
<div onchange="makeChange()">
{{ patient.birth }}
</div>
</form>
Argument passed to Date constructor should be in correct format.
In your case patient.birth should be string just like in your example: "06/24/2008".
You can not say like so:
const date = new Date("3 1930");
It prints
Invalid Date
https://www.tutorialspoint.com/javascript/javascript_date_object.htm

Cant quite invalidate/validate dates correctly (arrival date) ?

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}/.

Date of Birth Check using angular

I am new to angular and I am not sure how to work with dates. I have a form with name and date of birth.
Before submission I want to check if the person is older than 18 and show an error message before the form is submitted.
But I donot have access to the dob variable in the form unless it is submitted. In my code I have access to $scope.contact.dob only inside addContact(),( after the date is submitted). How do I do date of birth validations before form submission?
My code snippet is shown below
<form>
<input ng-model="contact.name">
<input ng-model="contact.dob" ng-min="minAge()">
<p ng-show="userForm.birthday.$error.min">Mustatleast 18.</p>
<button ng-click=addContact()></button>
</form>
my controller:
.controller("myctrl", function($scope){
$scope.addContact = fucntion(){
console.log($scope.contact)
$scope.contact.dob
}
$scope.minAge = function () {
var current = new Date();
var minYear = current.getFullYear() - 100;
var min = new Date(minYear,current.getMonth(),current.getDate()).toISOString();
return min;
};
})
In angular, while there is a directive for ng-minlength, there is no built-in-directive ng-min. Take a look at the documentation here.
https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D
Instead of ng-min, use the HTML min attribute.
Your code should look like this
<input ng-model="contact.dob" min="{{minAge()}}">
As for the error messages, you should take a look at ng-messages.

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

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