search

Home  >  Q&A  >  body text

Using JavaScript to retrieve data values ​​from my HTML and print them to the console

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粉381463780P粉381463780235 days ago464

reply all(1)I'll reply

  • P粉682987577

    P粉6829875772024-04-01 00:13:21

    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);
    }

    reply
    0
  • Cancelreply