Take select value with jquery

Asked

Viewed 47,097 times

3

I have an HTML code that contains the following information:

<select name="QtdAcomodacaoD" id="QtdAdomodacaoDuplo" class="form-control" style="width:130px" onchange="soma()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

And I’m trying to get the values with Jquery that way:

var QtdAcomodacaoD = $("#QtdAcomodacaoDuplo").val();

But when I give an Alert, Undefined appears.

4 answers

16


Try it like this:

$("#QtdAdomodacaoDuplo option:selected").each(function() {
   var QtdAcomodacaoD = $(this).val();
}); 

or:

var QtdAcomodacaoD = $("#QtdAdomodacaoDuplo option:selected").val();

4

In this case you can pick with val() or text() just add option:Selected to your selector:

 var itemSelecionado = $("#QtdAdomodacaoDuplo option:selected");

 document.write(itemSelecionado.text() + ' text()<br>');

 document.write(itemSelecionado.val() + ' val()');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<select name="QtdAcomodacaoD" id="QtdAdomodacaoDuplo" class="form-control" style="width:130px" onchange="soma()">
  <option value="1" selected>1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
<br>

2

These are good, but to work in real time, you have to do it this way:

$('.select-estados').change(function (){
     console.log($(this).val());
 });

when the change in values occurs, displays the selected, ai Voce can store in a variable this way:

$('.select-estados').change(function (){
    var cidade = ($(this).val());
    console.log(cidade);
 });

then you can make calls with AJAX, and populate your tags.

To get the value of the option you make:

 $('.select-estados').change(function (){
     console.log($('.select-estados option:selected').val());
 });

0

Beware of events that use classes, they may contain other elements. In the previous example, if the class . select-states had other elements it could result in error. The correct thing to do is:

    $('.select-estados').change(function(event){
   var cidade = event.currentTarget.value;
   alert(cidade);
 });
<!DOCTYPE html>
<html>
<body>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>

<select id="id_do_select" class="select-estados" data-placeholder='Nenhum valor selecionado...'>
    <option value="valor 1">Texto 1</option>
    <option value="valor 2">Texto 2</option>
    <option value="valor 3">Texto 3</option>
</select>

</body>
</html>

The safest is to use the currentTarget.

See how it works in this link.

Browser other questions tagged

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