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.
2
Answers
It is impossible using the standard DOM select
Here is a select2 version
One possible solution, is to add a
disabled
option
in the position you want, eg:if you place this approximately 10 values below the one you want in the middle, then (in my version of Chrome at least) when the user drops down the
select
, the value you want will be in the middle.This may be browser dependent.
(jquery just to populate the select, not needed otherwise)
While this may provide a solution, tbh, it looks a but rubbish. I recommend a third-party plugin / drop-down replacement, but this may be a solution if that’s not an option.