Home / Admin / Date field — Calculates a future date in a WPForms Date field based on a Number field — add n days to today
Duplicate Snippet

Embed Snippet on Your Site

Date field — Calculates a future date in a WPForms Date field based on a Number field — add n days to today

Ralden Souza PRO
<10
Code Preview
php
<?php
/**
 * Calculates a future date in a WPForms Date / Time field based on a Number field.
 * Form ID: 775
 * Number Field ID: 1
 * Date Field ID: 4
 */
function wpf_custom_date_calculator_script() {
?>
<script type="text/javascript">
	jQuery(function($) {
		// Define your form and field IDs
		const formId      = '#wpforms-form-775';
		const numberField = $('#wpforms-775-field_1');
		const dateField   = $('#wpforms-775-field_4');
		// Function to format a date object as MM/DD/YYYY
		function formatDate(date) {
			let month = String(date.getMonth() + 1).padStart(2, '0');
			let day   = String(date.getDate()).padStart(2, '0');
			let year  = date.getFullYear();
			return `${month}/${day}/${year}`;
		}
		// 1. Set the initial date to today and make the field fully read-only
		const today = new Date();
		dateField.val(formatDate(today));
		dateField.prop('readonly', true); // Prevents keyboard input.
		dateField.css('pointer-events', 'none'); // Prevents mouse clicks and the date picker from opening.
		// 2. Listen for changes in the "Numbers of days" field
		numberField.on('input', function() {
			
			// Get the number of days to add, default to 0 if empty
			const daysToAdd = parseInt($(this).val(), 10) || 0;
			
			// Create a new date object for today to perform the calculation
			const futureDate = new Date();
			
			// Add the specified number of days
			futureDate.setDate(futureDate.getDate() + daysToAdd);
			
			// Update the date field with the newly calculated date
			dateField.val(formatDate(futureDate));
		});
	});
</script>
<?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_custom_date_calculator_script' );

Comments

Add a Comment