I have this piece of code, I'm trying to log the selected value of the dropdown but for some reason only "1" get logged. How to fix this?
var select = document.getElementById("numOfPieces");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
var value = select.options[select.selectedIndex].value;
console.log(value);
select.onchange = function() {
console.log(value);
}
1) You are grabbing the value before onChange even called, but you should use the value after the onChange event.
select.onchange = function(e) {
// change
let value = select.options[select.selectedIndex].value;
console.log(value);
}
when you are taking the value of select.selectedIndex before the event then its value is 0 that's why it always gives you the value of the element at 0 index.
Instead what you should do is to get the select.selectedIndex value after the change event gets triggered.
var select = document.getElementById("numOfPieces");
var options = ["1", "2", "3", "4", "5"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
select.onchange = function(e) {
// change
let value = select.options[select.selectedIndex].value;
console.log(value);
}
<select name="numOfPieces" id="numOfPieces"></select>
2) You can also achieve the same result using addEventListener
var select = document.getElementById("numOfPieces");
var options = ["1", "2", "3", "4", "5"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
select.addEventListener("change", e => {
const value = e.target.value;
console.log(value);
})
<select name="numOfPieces" id="numOfPieces"></select>
You are printing the var value, not value from your onChange function. If you want to get the value from your select you need to change your function to receive the onChange event.
const select = document.getElementById("selectField");
select.addEventListener(
'change',
function() { console.log(this.value); },
false
);
<select name="selectField" id="selectField">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
or
const select = document.getElementById("selectField");
select.onchange = function() { console.log(this.value); };
<select name="selectField" id="selectField">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
This way the value you are printing refer to the this keyword, which inside the context refers to the select element.