Grab the value of a select and play on js

Asked

Viewed 43 times

-2

Hello. Well, I’m learning programming yet, so I’m pretty beginner.

I want to get the value selected by the user:

<select class="selecionar" id="teste" name="teste">
  <option default disabled="disabled">Selecione uma opção</option>
  <option value="teste1.html">opção 1</option>
  <option value="teste2.html">opção 2</option>
</select>

and play the selected value in an ajax in js:

var pegar = document.getElementById("teste").value;

$.ajax({
    url: pegar,
    type: "GET",
    async: true,
    }

however, it only takes the first option from the list, not the one the user selected.

I can’t explain it right, sorry.

  • use so since you are using jquery: var pegar = $( "#teste" ).val();

  • It didn’t help. He keeps taking only the first one (which in this case is teste1.html). if I select option 2 (teste2.html) does not help, it continues in 1.

  • 1

    then you must be doing something wrong in your code, put all the code in the question, because what I suggested works well, see here: https://jsfiddle.net/Pontual/gspu5dbc/1/

  • 1

    I did it! I did "the same" as yours. However, instead of Alert, I created a variable and then set it in place of Alert. thanks!

1 answer

1

You can do it in two ways: javascript only or using the Jquery library.

Javascript

var select = document.querySelector('select');
select.addEventListener('change', function() {
  var option = this.selectedOptions[0];
  var texto = option.textContent;

  console.log(texto);
});
<select>
  <option value="1">item 1</option>
  <option value="2" selected>item 2</option>
  <option value="3">item 3</option>
</select>

Jquery

var select = document.querySelector('select');
select.addEventListener('change', function() {
  var option = this.selectedOptions[0];
  var texto = option.textContent;

  console.log(texto);
});
<select>
  <option value="1">item 1</option>
  <option value="2" selected>item 2</option>
  <option value="3">item 3</option>
</select>

Browser other questions tagged

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