Carol Kariuki Carol Kariuki - 2 months ago 10
HTML Question

Get selected value of dropdown

I'm having a rather different structure of html and I am trying to get the selected value of a dropdown list as seen in the below code.



<div class="quantityDropdown quantityDropdown-cartItem">
<select id="qtySelect-61224b70-7b26-11e6-91d5-6921d6fe7421" class="cart-quantity-picker" data-orderitem="61224b70-7b26-11e6-91d5-6921d6fe7421">

<option value="1">
1
</option>

<option value="2" selected="">
2
</option>

<option value="3">
3
</option>

<option value="4">
4
</option>





My code returns null

Here is how I'm doing it. I want to get 2 as my value. As you can see, there's no value in the "selected" attribute: How do I get the value 2 that's outside the option tag?



var quantity = document.querySelector(".quantityDropdown select").getAttribute("selected");





Please help.

Answer

This will give you the value of the selected item:

quantity = document.querySelector(".quantityDropdown select").value;

However if you want the actual content of the selected item (i.e. the text shown) outside of the option tag, use:

var quantity = document.querySelector(".quantityDropdown select")[document.querySelector(".quantityDropdown select").selectedIndex].innerHTML;