I don't know what this code is doing wrong, I looked it up online and all I saw was putting window.onload = function() at the beginning of the code. However, the value always prints as null and I can't understand why it does this.
This is the code:
window.onload = function () {
// Get the select element by its id
const select = document.getElementById("select-filter");
// Get the selected option element
const selectedOption = select.options[select.selectedIndex];
// Get the data-select value
const dataSelect = selectedOption.getAttribute("data-sel");
// Print the data-select value to the console
console.log(dataSelect);
}
<div class="filter-select-container">
<!-- filter selector -->
<div class="filter-selection-container">
<select name="select-filter" id="select-filter">
<option value="filter-all">All</option>
<option value="filter-commercials" data-sel="1">Commercials</option>
<option value="filter-fiction" data-sel="2">Fiction</option>
<option value="filter-music-videos" data-sel="3">Music Videos</option>
</select>
</div>
</div>
thanks for your help:)
You probably mean
selectto have achangelistener and then check if the data property is defined before trying to log.const select = document.getElementById("select-filter"); select.addEventListener('change', handleChange); function handleChange() { const selectedOption = select.options[select.selectedIndex]; const dataSelect = selectedOption.getAttribute("data-sel"); if (dataSelect) console.log(dataSelect); }