Jquery if checkbox is checked then set date field to today's date

scameron
Participant

Hi there, I'm a bit of a newbie to coding, so bear with me! I have a HS landing page with a form on it. That form has a checkbox on it, and when someone checks that checkbox, I want to stamp a hidden date field with the current date. 

 

I've figured out the code to stamp the date, but not how to create the "if" condition so that this only happens when the checkbox is checked.

 

I'd really appreciate any help the community can offer me!

 

Here's my code so far:

 

<script>
jQuery(window).load(function(){
var today = new Date();
var formattedDate = today.toISOString().substr(0, 10);
$('#datePicker').val(formattedDate);
jQuery('input[name="free_trial_requested_date"]').val(formattedDate).change();

});
</script>

 

The ID of the checkbox in question is 'free_trial-a0608173-d2a2-4830-890c-e0e62ecfb82c_2953'

0 Upvotes
7 Replies 7
dennisedson
Community Manager

Hey @scameron 

Welcome to the world of coding!

This one looks like it is right up @piersg 's alley 😀

Thanks,

Dennis




Check out our Community Developer Blog
where we feature our Community driven developer podcast and how to content
0 Upvotes
piersg
Key Advisor

Hi @scameron (thanks @dennisedson). I'd do it like the below. You want to do it on the change event of the checkbox, rather than the page load (window.load function) that you're doing now.

<script>
$("[id or class of the checkbox]").change(function() {
    if(this.checked) {
      var today = new Date();
      var formattedDate = today.toISOString().substr(0, 10);
      $('#datePicker').val(formattedDate);
      $('input[name="free_trial_requested_date"]').val(formattedDate).change();
    }
});
</script>

 

scameron
Participant

Thanks so much @piersg! I tried it and it doesn't seem to be working, did I use the ID incorrectly maybe? 

 

<script>
$(["free_trial-a0608173-d2a2-4830-890c-e0e62ecfb82c_2109"]).change(function() {
if(this.checked) {
var today = new Date();
var formattedDate = today.toISOString().substr(0, 10);
$('#datePicker').val(formattedDate);
$('input[name="free_trial_requested_date"]').val(formattedDate).change();
}
});
</script>

0 Upvotes
piersg
Key Advisor

Hmm.. can you link the page so I can give a specific answer please?

0 Upvotes
piersg
Key Advisor
$("input[name='free_trial']").change(function() {
    if(this.checked) {
        var today = new Date();
        var formattedDate = today.toISOString().substr(0, 10);
        $('#datePicker').val(formattedDate);
        $('input[name="free_trial_requested_date"]').val(formattedDate).change();
    }
});
scameron
Participant

Thank you. Hmm, that didn't work and so I changed the first line from

$("input[name='free_trial']").change(function() {

  to

$('input[name="free_trial"]').change(function() {

To see if that worked better, and weirdly it seemed to work twice randomly, but not everytime

0 Upvotes