Would you like to know how to receive the value of my select by clicking on an option with pure javascript?

Asked

Viewed 50 times

1

I need to receive these values without there being a button, just by clicking on the field. The select has more than 50 option from a PHP loop.

<select>
  <option value="campo1">campo1</option>
  <option value="campo2">campo2</option>
  <option value="campo3">campo3</option>
...
</select>

2 answers

0

Use the Javascript onchange event. So, every time a change occurs in select, the function alteraValor will be called, in which case will print on the console the recovered value.

function alteraValor() {
  var selectElement = document.getElementById("select")
  var valorSelecionado = selectElement.value
  console.log(valorSelecionado)
 }
<select id="select" onchange="alteraValor()">
    <option value="campo1">campo1</option>
    <option value="campo2">campo2</option>
    <option value="campo3">campo3</option>
</select>

0


Just listen to the event change select and determine its value. You can at any time know the value using:

const select = document.querySelector('select');
console.log('O valor do select é ', select.value);

To know when the value changes you can use it like this:

const select = document.querySelector('select');
select.addEventListener('change', function(e) {
  const selectValue = this.value;
  alert(selectValue); // este é o valor que procuras
});
<select>
  <option value="campo1">campo1</option>
  <option value="campo2">campo2</option>
  <option value="campo3">campo3</option>
</select>

Browser other questions tagged

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