Carol Kariuki Carol Kariuki - 21 days ago 4
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">

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

<option value="3">

<option value="4">

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.


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;