我们可以选择出生年份。 从近几年的统计数据来看,大多数用户(接近70%)年龄在26-34岁之间。 当用户打开选择时,我们希望它从 1994 年左右(或 30 岁)开始,但如果不选择“1994”作为默认值,我们似乎无法实现此目的。
我不想默认选择 1994,因为我想检查该选择是否确实被选中。
这是我们当前的选择设置:
<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>
我正在寻找 javascript/jquery 解决方案。发现并尝试了这个:
$(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;
});
但这仍然选择“1994”选项,这与仅将选中的内容放在 1994 选项上而不是在打开选择时滚动到该位置没有什么不同。
使用标准 DOM select 是不可能的
这是一个 select2 版本
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>