My HTML
<form id="form">
<div id="tshirtOrder">
<button id="tshirt">T-Shirt</button>
<label>Quantity:</label>
<select name="tshirtQuantity" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
My JS
const getForm = () => {
const formEl = document.getElementById('form')
let tshirtQuantity = formEl.elements.tshirtQuantity.value
}
I am trying to sell t-shirt item with the quantity option (number value) as a drop-down list. My question is how can write a syntax to return the quantity given in number of the value 1, 2, 3? The JavaScript I wrote always return the first option value (1) inside of <select name="tShirtQuantity">. I want to query the correct number value that the user selected from the drop-down menu. Thanks!
You can use querySelectorAll, spread operator and map function as
let selectElement = document.querySelectorAll('[name=tshirtQuantity]');
let optionValues = [...selectElement[0].options].map(o => parseInt(o.value))
If you only want to get selected value
console.log(selectElement[0].options[selectElement[0].selectedIndex].value)
const getForm = () => {
let selectElement = document.querySelectorAll('[name=tshirtQuantity]');
let optionValues = [...selectElement[0].options].map(o => parseInt(o.value));
console.log(optionValues);
console.log(selectElement[0].options[selectElement[0].selectedIndex].value)
}
getForm();
<form id="form">
<div id="tshirtOrder">
<button id="tshirt">T-Shirt</button>
<label>Quantity:</label>
<select name="tshirtQuantity" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</form>
The following method is old school solution.
Replace:
let tshirtQuantity = formEl.elements.tshirtQuantity.value
with:
let tshirtQuantity = formEl.elements.tshirtQuantity.options[formEl.elements.tshirtQuantity.selectedIndex]
There are a few problems with your code.
First, the HTML. You are closing the label in the wrong place, and the HTML element you should listen to is not the form, but the select.
<form id="form">
<div id="tshirtOrder">
<label>Quantity:
<select class="tshirt" name="tshirtQuantity" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</label>
</div>
</form>
Then, to get the change on the element, you should add an event listener that reacts to the change.
const selectElement = document.querySelector('.tshirt');
selectElement.addEventListener('change', (event) => {
console.log(event.target.value)
});
You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event