CMS Development

Pnaumenko
Member

How to set a value for the date field with JavaScript?

Hi there.

What is the correct way to set a value in the date field with JavaScript?
I'm doing it with the code

 

 

 

const date = new Date().toISOString().slice(0, 10);
$('[name="game_date"]').val(date).change();

 

 

 

 

But,  we are getting empty value for "game date" field in submissions on form sumbit.

 
 
 
 
 
 
 
 
 
0 Upvotes
4 Replies 4
BarryGrennan
Top Contributor

How to set a value for the date field with JavaScript?

Oh, also you're calling dateVal which is undefined instead of date, so it'd be:

 

window.addEventListener('message', event => {
   if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
const date = new Date().toISOString().slice(0, 10);
$('[name="date_of_birth"]').val(date).change();
   }
});

 

I've tested it and it seems to work as you intend.


profile2022aBarry Grennan

Freelance HubSpot CMS Developer

Website | Contact | LinkedIn

 

 

BarryGrennan
Top Contributor

How to set a value for the date field with JavaScript?

Hi @Pnaumenko , you might need to elaborate on what the project is a bit. And let us know if the field appears to be set prior to submission.

 

But my first suggestion would be that you need to wrap any javascript intended to affect a form in a global event listener.

 Specifically the on FormReady listener. e.g.

 

 

window.addEventListener('message', event => {
   if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
       console.log("Form Loaded!");
/* Your code here */
   }
});

 

 


profile2022aBarry Grennan

Freelance HubSpot CMS Developer

Website | Contact | LinkedIn

 

 

Pnaumenko
Member

How to set a value for the date field with JavaScript?

@BarryGrennan Thank you for your response, 'dateVal' was a typo in my example.
To be clear, this code runs on a button click and copies a value from the custom date picker to the Form's field.
It works okay before submitting the form or focusing on any form field when running HubSpot's validation (in my understanding). After that, it clears the value of the date field, other non-date fields are good

0 Upvotes
BarryGrennan
Top Contributor

How to set a value for the date field with JavaScript?

Hi @Pnaumenko, could you perhaps share your code so we can troubleshoot?

 

Have you wrapped it in the FormReady event listener?


profile2022aBarry Grennan

Freelance HubSpot CMS Developer

Website | Contact | LinkedIn