How to Dynamically Display Years in Your Forms

Introduction

Would you like to dynamically display years inside your form? Using a little JavaScript you can easily have a year or years automatically move forward. In this tutorial, we’re going to create a school registration form and use JavaScript to dynamically update the years for each new school year.

Creating the form

We’ll begin by creating a new form and at the very top of the form, we’re going to add an HTML form field. This will have a mixture of text and HTML so we can dynamically display the title which will include the current school year.

Once you’ve added your HTML field, you’ll need to add inside your Code section.

You can select this text and copy it to add it to your form.

<h1>School Registration</h1>
<h2>For the school year <span id="last-year"></span> to <span id="next-year"></span></h2>

Inside each of the span IDs, a year will dynamically be added. For example, inside the last-year will contain the beginning school year and inside the next-year will contain the ending school year.

add the HTML code to your form so it will dynamically display the years for your school year

If you need any help in creating your form, please review this documentation.

Adding the snippet

Now it’s time to add the snippet that will populate these years for us.

If you’re not sure how or where to add snippets, please check out this tutorial.

/**
 * Change the position of the date picker popup
 *
 * @link https://wpforms.com/developers/how-to-dynamically-display-years-in-your-forms/
 */

function wpf_dev_dynamic_school_year( ) {
?>
 
<script type="text/javascript">
	
	window.onload = function() {
        
		document.getElementById( "next-year" ).innerHTML = new Date().getFullYear();
        document.getElementById( "last-year" ).innerHTML = new Date().getFullYear() - 1;

	};

    </script>
 
<?php
}
 
add_action( 'wpforms_wp_footer_end', 'wpf_dev_dynamic_school_year', 30 );

With this snippet we’re pulling the current year to display for the next-year and for the last-year we’re taking the current year and using math subtracting one year.

now the form will display the current year as well as the current year minus one year

And that’s it! Would you like to also provide a live word count under your text field? Take a look at our tutorial on How to Display a Total Word Count Under Your Form Field.

Action Reference: wpforms_wp_footer_end