Get select value with jquery

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 like this:

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

But when I give an alert, Undefined appears.

    
asked by anonymous 04.01.2016 / 20:49

2 answers

6

Try this:

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

or:

var QtdAcomodacaoD = $("#QtdAdomodacaoDuplo option:selected").val();
    
04.01.2016 / 20:57
2

In this case you can get val () or text () just add option: selected in 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><selectname="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>
    
04.01.2016 / 21:02