(function ($) { Drupal.behaviors.dateYearRange = {}; Drupal.behaviors.dateYearRange.attach = function (context, settings) { var $textfield, $textfields, i; // Turn the years back and forward fieldsets into dropdowns. $textfields = $('input.select-list-with-custom-option', context).once('date-year-range'); for (i = 0; i < $textfields.length; i++) { $textfield = $($textfields[i]); new Drupal.dateYearRange.SelectListWithCustomOption($textfield); } }; Drupal.dateYearRange = {}; /** * Constructor for the SelectListWithCustomOption object. * * This object is responsible for turning the years back and forward textfields * into dropdowns with an 'other' option that lets the user enter a custom * value. */ Drupal.dateYearRange.SelectListWithCustomOption = function ($textfield) { this.$textfield = $textfield; this.$description = $textfield.next('div.description'); this.defaultValue = $textfield.val(); this.$dropdown = this.createDropdown(); this.$dropdown.insertBefore($textfield); }; /** * Get the value of the textfield as it existed on page load. * * @param {String} type * The type of the variable to be returned. Defaults to string. * @return * The original value of the textfield. Returned as an integer, if the type * parameter was 'int'. */ Drupal.dateYearRange.SelectListWithCustomOption.prototype.getOriginal = function (type) { var original; if (type === 'int') { original = parseInt(this.defaultValue, 10); if (window.isNaN(original)) { original = 0; } } else { original = this.defaultValue; } return original; }; /** * Get the correct first value for the dropdown. */ Drupal.dateYearRange.SelectListWithCustomOption.prototype.getStartValue = function () { var direction = this.getDirection(); var start; switch (direction) { case 'back': // For the 'years back' dropdown, the first option should be -10, unless // the default value of the textfield is even smaller than that. start = Math.min(this.getOriginal('int'), -10); break; case 'forward': start = 0; break; } return start; }; /** * Get the correct last value for the dropdown. */ Drupal.dateYearRange.SelectListWithCustomOption.prototype.getEndValue = function () { var direction = this.getDirection(); var end; var originalString = this.getOriginal(); switch (direction) { case 'back': end = 0; break; case 'forward': // If the original value of the textfield is an absolute year such as // 2020, don't try to include it in the dropdown. if (originalString.indexOf('+') === -1) { end = 10; } // If the original value is a relative value (+x), we want it to be // included in the possible dropdown values. else { end = Math.max(this.getOriginal('int'), 10); } break; } return end; }; /** * Create a dropdown select list with the correct options for this textfield. */ Drupal.dateYearRange.SelectListWithCustomOption.prototype.createDropdown = function () { var $dropdown = $('