Adobe Pro, PDF form with javascript - javascript

I have created a form in Adobe Pro and i have added some JavaScript to it. But i have two problems.
1) Is there a "Document Finished Loading"-action? I have a date field on the form and i would like that it automatically adds todays date into that field when the user opens the document to fill in the form fields.
2) The date method that i am using doesn't work properly, i have this code:
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth();
var year = dt.getFullYear();
var dagensdatum = year + "-" + month + "-" + day;
var datum = this.getField("Datum");
datum.value = dagensdatum;
datum = this.getField("Datum2");
datum.value = dagensdatum;
datum = this.getField("Datum3");
datum.value = dagensdatum;
But when i run this, it prints out 11th of April and not todays date. Any ideas?

for your 2nd question I don't know why the date is not correct, but at least, you should do this :
var month = dt.getMonth();
month++;
because the getMonth() returns an int between 0 and 11. As for the day, I don't know what could cause the problem.
Edit : Have you checked your own date on your computer? Because if it is wrong it will be displayed uncorrectly in your browser. I guess you should have a date of 11th May in your computer, don't you?

Related

How do I add 1 to a date in a query string with an onClick function?

I am trying to have previous day, current day, and next day buttons so for example, if I press the next button, it will take today's date, add one to today's date and show tomorrows information on the page.
My click handler looks like:
const nextHandler = () => {
let resDate = new Date();
let year = resDate.getFullYear();
let day = new Date().getDate();
let month = resDate.getMonth() + 1;
if (month.toString().length < 2 || day.toString().length < 2) {
month = ('0' + month).slice(-2);
day = ('0' + day).slice(-2);
}
day = parseInt(day) + 1;
let newDate = `${year}-${month}-${day}`;
// newDate --> 2021-04-11
history.push(`/dashboard?date=${newDate}`);
};
When I click my next button I get taken to: http://localhost:5000/reservations?date=2021-04-12 exactly as I would like. However, I am only able to add to the day once. How am I continuously able to update this query string?
You're only ever starting with new Date(); on your second line so it'll only ever increment once. You'll have to read from the querystring a value to put in new Date(VALUE); if it's set so that it continues to remember. Here's a stackoverflow answer from something like that: How can I get query string values in JavaScript?
You're code may look like:
const urlParams = new URLSearchParams(window.location.search);
const dateParam = urlParams.get('date');
let resDate = dateParam ? new Date(dateParam) : new Date();
It's nextHandler is using today's date to increment rather than the date of the query string.
On the first click, nextHandler today's date to increment. But, the next click should start from the date in the query string.
I hope that solve your problem.

Add 1 day to date from spreadsheet via Google App Script / Javascript- Month Keeps Reseting to current month

I am trying to set up a Google App Script function that grabs a date (formatted dd/mm/yy) from the last column of a spread, and creates a new column with the date + one day.
I have seen previous solutions and tried to use the same, i.e.newDate.setDate(lastDate.getDate()+1) but have had issues getting the value formatted correctly in the script. This is a variation of my code that I'm using to loop through for a year's worth of values to see what I get:
for (var i=0;i<365;i++){
var lastRow = outputSheet.getLastRow();
var newDate = new Date();
var lastDate = outputSheet.getRange(lastRow,1).getValue();
var newDateRng = outputSheet.getRange(lastRow+1,1);
Logger.log(lastDate + 1, typeof lastDate, typeof (lastDate + 1));
newDate.setDate(lastDate.getDate());
Logger.log(newDate);
newDate.setDate((newDate.getDate() + 1));
Logger.log(newDate);
var newDateFormatted = Utilities.formatDate(newDate, ss.getSpreadsheetTimeZone(), "dd/MM/YY");
Logger.log(newDateFormatted);
newDateRng.setValue(newDateFormatted);
}
With a start date of "01/03/2020", I get the following behaviour:
01/03/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
...
etc. All the way through the year. Although the day increase, the month seems to reset after the first day of the month.
As a note, I am specifically looking to pick the date off of the spreadsheet rather than using new Date as today and new Date +1 as tomorrow.
Thanks
You need to use a different variable in the loop otherwise you will always return to the same month.
Also avoid using strings for the result, keep date objects and display it properly.
The code goes like this :
function otherTest(){
var lastDate = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();
var date = new Date(lastDate); // create new date object
var result = [];
for (var i=0;i<365;i++){
date=new Date(date).setDate(new Date(date).getDate()+1)
Logger.log('date='+new Date(date))
result.push([new Date(date)]);
}
SpreadsheetApp.getActiveSheet().getRange(1,2,result.length,1).setValues(result).setNumberFormat('dd/MM/yyyy');
}

How to let my website tell what current day it is alongside with a nice string message?

I'm doing a javascript lab where my website user can simply click a button and the website will make an alert that first will show the date regularly and then the day with a string message.
<script type="text/javascript">
function dateFunction() {
var date = new Date();
var daysOfweek= ["Sunday",
"Monday","Tuesday","Wednesday","Thursday","Friday", "Saturday"];
alert(date);
var currentday = date.getDay();
alert("Happy " + weekdays[currentday] + "!");
}
</script>
Add a variable to get the day in number format. Today is Friday which is 5
Your weekdays[currentday] returns nothing because you didn't call it weekdays you called it daysOfweek
function dateFunction() {
var date = new Date();
var daysDigitized = date.getDay();
var weekdays= ["Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday", "Saturday"];
alert(date);
var currentday = date.getDay();
alert("Happy " + weekdays[daysDigitized] + "!");
}
Lastly, you never asked a question. I had to run your code to figure out there was a problem and what the problem was. So, really I'm just assuming this is what you need. Next time be sure and ask a specific question.
Updated per comments

How to calculate age from DOB if month is invalid?

I have a date field which accepts if the month is unknown. And I calculate the age from the date entered and the current date and time.
var birthDate = new Date("12 UNK 1995");
var now = new Date();
var age = now.getFullYear() - birthDate.getFullYear();
document.write("Your Age is: " + age);
If the run this is throwing me NaN error. I think it is because of that invalid date format.
Is there any way that I can calculate the age even if the month is unknown based on the year only in any kind of date formate?
If the month is unknown then the normal way programmatically to set it to the middle of the year – to July. I know this problem in India – some people do not know their birth date sometimes.
For example like follows:
var month = "UNK"; // TODO: here is your code to get the month name from field
month = month == "UNK" ? "JUL" : month;
var birthDate = new Date("12 " + month + " 1995");
var now = new Date();
var age = now.getFullYear() - birthDate.getFullYear();
document.write("Your Age is: " + age);
But note that your calculation is not really correct because you do not calculate with full date (day, month, year, hour, minutes).
My suggestion
But I would like to suggest to use a new HTML5 input field type date (see this link) which looks like follows (go with mouse pointer over this field):
<input name="birthdate" type="date" required>
And all users have to put in this date on their's own accountability. In this case they have to choose one date and you will do not have the accountability for this.
You have the year already in a string so extract it from the string and then substract from year now.

pre-populating date input field with Javascript

I am trying to prepopulate a date into an html "date" input field, but it ignores the values I try to pass:
<html>
...
<input id='date' type='date'>
...
</html>
<script>
...
var myDate = new Date();
$("#date").val(myDate);
...
I have also tried passing the date object as a string
var myDate = new Date().toDateString();
$("#date").val(myDate);
When I open the form, the date field is blank. If I eliminate the type="date" tag, the value shows up as a string, but then I don't have access to the datepicker. How do I pre-populate a date input and still have use of the datepicker? I'm stumped.
Thanks.
It must be set in ISO-format.
(function () {
var date = new Date().toISOString().substring(0, 10),
field = document.querySelector('#date');
field.value = date;
console.log(field.value);
})()
http://jsfiddle.net/GZ46K/
Why Not to Use toISOString()
The <input type='date'> field takes a value in ISO8601 format (reference), but you should not use the Date.prototype.toISOString() function for its value because, before outputting an ISO8601 string, it converts/represents the date/time to UTC standard time (read: changes the time zone) (reference). Unless you happen to be working in or want that time standard, you will introduce a bug where your date will sometimes, but not always, change.
Populate HTML5 Date Input from Date Object w/o Time Zone Change
The only reliable way to get a proper input value for <input type='date'> without messing with the time zone that I've seen is to manually use the date component getters. We pad each component according to the HTML date format specification (reference):
let d = new Date();
let datestring = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
document.getElementById('date').value = datestring;
/* Or if you want to use jQuery...
$('#date').val(datestring);
*/
<input id='date' type='date'>
Populate HTML5 Date & Time Fields from Date Object w/o Time Zone Change
This is beyond the scope of the original question, but for anyone wanting to populate both date & time HTML5 input fields from a Date object, here is what I came up with:
// Returns a 2-member array with date & time strings that can be provided to an
// HTML5 input form field of type date & time respectively. Format will be
// ['2020-12-15', '01:27:36'].
function getHTML5DateTimeStringsFromDate(d) {
// Date string
let ds = d.getFullYear().toString().padStart(4, '0') + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
// Time string
let ts = d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0') + ':' + d.getSeconds().toString().padStart(2, '0');
// Return them in array
return [ds, ts];
}
// Date object
let d = new Date();
// Get HTML5-ready value strings
let dstrings = getHTML5DateTimeStringsFromDate(d);
// Populate date & time field values
document.getElementById('date').value = dstrings[0]
document.getElementById('time').value = dstrings[1]
/* Or if you want to use jQuery...
$('#date').val(dstrings[0]);
$('#time').val(dstrings[1]);
*/
<input type='date' id='date'>
<input type='time' id='time' step="1">
Thank you j08691. That link was the answer.
To others struggling like me, when they say input is "yyyy-mm-dd" the MEAN it!
You MUST have 4 digits for the year.
You MUST have a dash and no spaces.
You MUST have 2 digits for day and month.
In my example myDate.getMonth for January would only return "1" (actually it returns "0" because for some reason javascript counts months from 0-11). To get this right I had to do the following:
var myDate, day, month, year, date;
myDate = new Date();
day = myDate.getDate();
if (day <10)
day = "0" + day;
month = myDate.getMonth() + 1;
if (month < 10)
month = "0" + month;
year = myDate.getYear();
date = year + "-" + month + "-" + day;
$("#date").val(date);
I hope this helps others not waste hours like I did testing this before October or before the 10th of the month! LOL
Here is an answer based on Robin Drexlers but in local time.
//Get the local date in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 10);
//Set the field value
var field = document.querySelector('#date');
field.value = datestr;
If it's a datetime field you're modifying (as opposed to just the date) don't forget to add the time T00:00, or change the substring to 16 characters for example:
//Get the local date and time in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 16);
//Set the field value
var field = document.querySelector('#datetime');
field.value = datestr;
This below code populates the local date . The accepted answer populates UTC date.
var date = new Date();
field = document.querySelector('#date-id');
var day = date.getDate();
if(day<10){ day="0"+day;}
var month = date.getMonth()+1;
if(month<10){ month="0"+month;}
field.value = date.getFullYear()+"-"+month+"-"+day;
I don't have the reputation points to comment on another answer, so I'll just add a new answer. And since I'm adding an answer, I'll give more details than I would've in a comment.
There's an easier way to zero pad than all of the juggling that everyone is doing here.
var date = new Date();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var year = date.getFullYear();
var htmlDate = year + '-' + month + '-' + day;
console.log("Date: " + htmlDate);
Today, the output would be
Date: 2020-01-07
The code is building a dynamic string by prepending a quoted zero, then taking the last 2 characters with slice(-2). This way, if the zero makes it 01, the last 2 are 01. If the zero makes it 011, then the last two are 11.
As for the month starting at zero silliness, you can also add 1 dynamically before prepending the zero and everything still works. You just have to do the math operation before turning it into a string.
As a side note, I've noticed that when you update a date field, you have to hide the field before setting the value and show it after setting. I don't do this often enough, so I have to re-struggle each time I need to deal with it. Hopefully this will help someone from the future.
waves to future people

Categories

Resources