skip to Main Content

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


  1. It is impossible using the standard DOM select

    Here is a select2 version

    const currentYear = new Date().getFullYear();
    const minAge = 18;
    const maxAge = 40;
    
    const $dob = $('#dob');
    
    for (let age = minAge; age <= maxAge; age++) {
      const birthYear = currentYear - age;
      $dob.append(`<option value="${birthYear}">${birthYear} (age ${age})</option>`)
    }
    
    
    $dob
      .select2({
        'width': '150px'
      })
      .select2('open');
    
    const targetValue = currentYear - 30;
    const $targetItem = $(`li.select2-results__option[id*="${targetValue}"]`);
    
    if ($targetItem.length > 0) {
      const $dropdown = $('.select2-results__options'); // This is the dropdown container
      $dropdown.scrollTop($targetItem.offset().top - $dropdown.offset().top + $dropdown.scrollTop());
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
    
    <select id="dob" name="dob">
      <option value="">Please select DOB</option>
    </select>
    Login or Signup to reply.
  2. One possible solution, is to add a disabled option in the position you want, eg:

    <option selected disabled>select year</option>
    

    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.

    for (let i=2024; i>1950; --i) {
      $("select").append(`<option>${i}</option>`);
      if (i == (2024-30-10))
        $("select").append(`<option selected disabled>select year</option>`);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <select>
    </select>

    (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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search