interact with Select option dynamically via javascript

Asked

Viewed 50 times

-2

I think this is already very simple, but unfortunately, the simplest is the most complicated for me to understand. lol

my goal is simple and summarizing it further, make sure that when you select a select option, based on the value of the option, something in html would be written, but for some reason, even if I change and remake and even almost copying a code ( what made me create this account here and ask this question) the value selected was always "1". I will write an html/js

**HTML**
<div id="escrever"> </div>
<select name="prazo" id="prazoTest">
    <option value="1">1 dia</option>
    <option value="2">2 dias</option>
    <option value="4">4 dias</option>
    <option value="6">6 dias</option>
    <option value="7">1 semana</option>
</select>

js to show the problem that occurred.

const selecter = document.getElementById('prazoTest')
const valueSelect = selecter.options[selecter.selectedIndex].value
const modificar = document.getEelementById('escrever')
            
function passarAfaca() {
    console.log(valueSelect)
    modificar.innerHTML = valueSelect
}
selecter.onchange = passarAfaca

1 answer

1

To record an event listening in an element use the method Element.addEventListener(), pass in the first parameter the type of event that will remain in wait and in the second a function you will receive a notification when an event of the specified type occurs.

const selecter = document.getElementById('prazoTest')
const modificar = document.getElementById('escrever')

selecter.addEventListener("change",function (e){
  console.log(e.target.value);
  modificar.innerText = e.target.value;
});
<div id="escrever"> </div>
<select name="prazo" id="prazoTest">
  <option value="1">1 dia</option>
  <option value="2">2 dias</option>
  <option value="4">4 dias</option>
  <option value="6">6 dias</option>
  <option value="7">1 semana</option>
</select>

Browser other questions tagged

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