I have this Select dropdown with years. When each year selected the div according to the class will show and others will be hidden. Pretty straight forward. But the issue is, on page load it shows all divs first until I change the selection to 2021. It should show 2020 div first only since it is the selected value. Here is my code.
$(document).ready(function () {
$('#event-slider').on('change', function () {
if (this.value == '2020') {
$(".2020").show();
$(".2021").hide();
} else {
$(".2020").hide();
}
if (this.value == '2021') {
$(".2021").show();
$(".2020").hide();
} else {
$(".2021").hide();
}
});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<form class="needs-validation" novalidate autocomplete="off">
<select class="custom-select" id="event-slider">
<option value="2020" selected>2020</option>
<option value="2021">2021</option>
</select>
</form>
<div class="2020"><p>Year 2020</p></div>
<div class="2021"><p>Year 2021</p></div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
This is the solution I've worked on but seems the problem still exists.
$('select[id^="event-slider"] option[value="2021"]').attr("selected","selected");
If anyone knows a better solution or any mistake I've done please help me. Much appreciated. Thank you