Onchange does not fire

Asked

Viewed 39 times

0

Oie! So I’m unable to add an event onchange on my select tag.

HTML

<select class="onchange">
  <option>Selecione um assunto:</option>
  <option value="pratica">Receita de pães caseiros</option>
  <option value="pao">Outras iniciativas Waldorf em Brasília</option>
  <option value="waldorf">Boas práticas para tempos de pandemia</option>
</select>

I want that when an option is selected, the session with identical id will appear. But I can’t even add the onchange event. I’ve tried several different codes, but the console doesn’t even appear.

JS

//grab all ids
sectionTag.forEach(function(section){
  id = section.getAttribute("id")
  console.log(id)
})

const value = select.options[select.selectedIndex].text;

//grab values
select.addEventListener("onchange", function(event){
  console.log(value)
})

I wonder if someone could help me?

  • 1

    It’s probably 'cause addeventlistener() is not onchange, but, yes only change!

  • Simmmm! Now it worked ahsuahs Ai thank you so much!! was suffering here aushuash @Leandrade

  • 1

    Blza Mari, Javascript is kind of tricky when it comes to names from time to time! Something else there you don’t even need to catch the Event just declare ownership this which will be related to the select option so: console.log(this.value).

1 answer

0

Your select is wrong, onchange is not a class but an event, so what you need to do is assign your event to it. There are several ways to get the values, a very simple one would be this:

<select id="assunto" onchange="getAssunto()">
  <option>Selecione um assunto:</option>
  <option value="pratica">Receita de pães caseiros</option>
  <option value="pao">Outras iniciativas Waldorf em Brasília</option>
  <option value="waldorf">Boas práticas para tempos de pandemia</option>
</select>

And in your JS Voce takes and uses the way you want:

function getAssunto() {
    let assunto = document.getElementById('assunto').value;
    console.log(assunto);
  }

Vote positive if it helped you :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.