Using JavaScript to retrieve data values ​​from my HTML and print them to the console
P粉381463780
P粉381463780 2024-03-31 13:31:58
0
1
399

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:)

P粉381463780
P粉381463780

reply all(1)
P粉682987577

You probably mean select to have a change listener 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);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!