We have this select to select year of birth.
Looking at the statistics of last couple of years, most users (close to 70%) are between the ages of 26-34.
When the user opens the select, We want it to start at around 1994 (or age 30), but without selecting ‘1994’ as a default, we can’t seem to make this work.
I do not want 1994 selected by default, as I want to check if the select is actually selected.
This is our current setup for the select:
<select name="year" required>
<option value="" disabled selected> - </option>
<?php for ($i = date('Y') - 110; $i <= date('Y'); $i++) : ?>
<option value="<?php echo $i; ?>" <?php if ($i == $year) echo 'selected'; ?>>
<?php echo $i; ?>
</option>
<?php endfor; ?>
</select>
I’ve looked for a javascript/jquery solution. Found and tried this:
$(document).ready(function() {
const yearToScroll = 1994;
const birthYearSelect = $('#geboortedatum_jaar');
// Find the option index of 1994
const optionIndex = birthYearSelect.find('option[value="' + yearToScroll + '"]').index();
// Set the scroll position of the dropdown to show 1994
birthYearSelect.prop('selectedIndex', -1); // Ensures no option is selected
birthYearSelect[0].selectedIndex = optionIndex;
});
But this still selects the ‘1994’ option, making it no different from just putting selected on the 1994 option and not just scroll to that position when opening the select.