Recent searches


No recent searches

Help Center Form - Date Picker Set by Javascript



Posted Jun 22, 2023

Hi! I have two custom fields on my Help Center form, both are date-picker fields. I am looking to auto-set the second field when the first field changes.

The two fields are similar to reservation fields, like a "check in" and "check out" date. When the "check in" date is selected, I would like the "check out" date to auto-set to the "check in" date, so its easier for the user to find their "check out" date. 

Ideally, it would be great to only do this when the "check out" date is null, and to set the "check out" to 1 day after the "check in" by default, but for now just matching the two fields would be a great start!

I was able to get the following code to work (just as a starting place):

document.addEventListener('DOMContentLoaded', function() {

$('#request_custom_fields_1').val("2022-02-01");
$('#request_custom_fields_2').val($('#request_custom_fields_1').val());

})

So I got the two fields talking to each other (when the first field is manually set by code rather than by user).  I need to now set it so it changes when the USER updates the first field. I tried some various online solutions about using the change event, but it didnt work.

 

Any ideas? Seems like a good ask for Ifra Saqlain if they are available :)


0

10

10 comments

image avatar

Ifra Saqlain

Zendesk LuminaryMost Engaged Community Member - 2022Most Engaged Community Member of The Year - 2021Community Moderator

Hey Alek Reed, try this plugin, it works amazing as you want, also I tried it for my form -

https://jqueryui.com/datepicker/#date-range

 

If any issue occurs during the implementation, let me know :)

Thanks

0


Ifra Saqlain I tried using the following per your link and its not setting the restrictions.  <script>
 $( function() {
   $( "#request_custom_fields_XXXXXXXXXXX" ).datepicker({ minDate: -20, maxDate: "+1M +10D" });
 } );
 </script>

0


@Ifra Saqlain When I use the following it shows another calendar and doesnt effect the popup calendar, I'm not sure what the selector should be.:  

document.addEventListener('DOMContentLoaded', function() {

var datePicker = $("#new_request > div.form-field.string.required.request_custom_fields_1");


    // Initialize the datepicker with debugging
    datePicker.datepicker({
      minDate: +60, // 20 days in the past
      maxDate: "", // 1 month and 10 days in the future
      onSelect: function(selectedDate) {
        console.log("Selected date: " + selectedDate);
      }
    });

    // Debugging: Log the current settings to verify
    console.log("Datepicker minDate: ", datePicker.datepicker("option", "minDate"));
    console.log("Datepicker maxDate: ", datePicker.datepicker("option", "maxDate"));
    
})

0


image avatar

Ifra Saqlain

Zendesk LuminaryMost Engaged Community Member - 2022Most Engaged Community Member of The Year - 2021Community Moderator

Hi Mr. Dustin Swayne,

I'll get back to you soon :)

 

Thanks

1


Ifra Saqlain Trying to set the minDate of the calendar to 60+ days from today's date so that no dates prior to 60 days out can be selected.  Is this possible with javascript or is it something with pikaday?

 

Thanks for your help in advance.

0


@Ifra Saqlain 

I was able to get the following to work, however, I cannot clear the date after alert automatically.  Any thoughts?

 

$(document).on('change', 'input.datepicker', function() {
    // Check if the related field value is "rent_increase"
    if ($("#request_custom_fields_2xxxxxx").val() == "xxx_xxxx") {  
        var inputDateString = $(this).val(); // Fetch the input value

        // Parse the input date string assuming format "Month day, year"
        var parts = inputDateString.match(/(\w+) (\d+), (\d+)/);
        if (!parts) {
            alert('Invalid date format. Please enter a date in the format "Month day, year" (e.g., "May 4, 2024").');
            $(this).val(''); // Clear the input if the format is not correct
            return; // Exit the function if the format is incorrect
        }

        // Create a Date object from the parsed date string
        var inputDate = new Date(parts[3], new Date(Date.parse(parts[1] + " 1, 2012")).getMonth(), parts[2]);

        // Set today's date with time reset to midnight for accurate comparison
        var today = new Date();
        today.setHours(0, 0, 0, 0);

        // Calculate the date 60 days from today
        var sixtyDaysFromToday = new Date(today);
        sixtyDaysFromToday.setDate(today.getDate() + 60);

        // Compare the input date to the date 60 days from today
        if (inputDate > sixtyDaysFromToday) {
            console.log('The selected date is greater than 60 days from today.');
        } else {
            alert('Please select a date that is more than 60 days from today.');
            datepicker.setDate(null) // Optionally clear the invalid input
        }
    }
});

0


Was able to fix it by adding these two lines after the alert:

 

$('.datepicker').val(''); // Optionally clear the invalid input
$('#request_custom_fields_2xxxxxx').val('');

 

0


Ifra Saqlain any luck on being able to set min or max date range with the date picker in the form?

0


image avatar

Ifra Saqlain

Zendesk LuminaryMost Engaged Community Member - 2022Most Engaged Community Member of The Year - 2021Community Moderator

Hi Mr. Dustin,

 

Please try this code to set the minimum and max date in the above plugin.

 

 $( function() {

 $( "#request_custom_fields_103412xxxxxxx" ).datepicker({
  maxDate: "+1m +1w"
});
 $( "#request_custom_fields_179012xxxxxx" ).datepicker({
      minDate: "-1m +1w"
});
    // Getter
var maxDate = $( "#request_custom_fields_103412xxxxxxx" ).datepicker( "option", "maxDate" );
     // Getter
var minDate = $( "#request_custom_fields_179012xxxxxx" ).datepicker( "option", "minDate" );
    
// Setter
$( "#request_custom_fields_103412xxxxxxx" ).datepicker( "option", "maxDate", "+1m +1w" );
// Setter
$( "#request_custom_fields_179012xxxxxx" ).datepicker( "option", "minDate", "-1m +1w" );

  } );

 

0


image avatar

Jérémy

Zendesk Customer Care

Hi Dustin Swayne 

 

I believe the issue with this approach is exactly that:

 

When I use the following it shows another calendar and doesn't effect te popup calendar

 

To work around the problem while still using the method Ifra suggested, here is how you could potentially make it work:

 

$(document).ready(function() {
	$(".datepicker").remove();
	let myCustomDatePicker = '<input type="text" id="myCustomId">'
	$("#request_custom_fields_XYZ_label").after(myCustomDatePicker);
	$("#myCustomId").datepicker({minDate: +0, maxDate: +60, altField: "#request_custom_fields_XYZ", altFormat: "yy-mm-dd"});
	$("#myCustomId").on("change", function() {
		$("#myCustomId").datepicker("option", "dateFormat", "MM d, yy");
	});
});	

 

The idea is to completely get rid of the native field (be mindful of which element(s) you remove - I only had 1 date field in the form when testing) and create your own custom one while replicating the logic that makes it sync to the backend (as a bonus, you can even choose the way it displays in the field after a selection).

 

You can add some extra logic to check for a specific form, etc… if needed.

 

Of course, remember to:

  • Import jQuery and jQuery UI
  • Style the new field (the jQuery UI stylesheet does the trick)

 

I hope that helps!

0


Please sign in to leave a comment.

Didn't find what you're looking for?

New post