Good day, seniors!
Ignore the choice of ids, names, names of variables. I was just testing this code first before putting it in the project I’m working on. Thank you in advance!
I can’t seem to get the selected value of the select element and add it in an array of object
here’s the code:
let list = [];
let selectedVal;
function changes(event) {
selectedVal = event.target.value;
list.push({
selectedVal
})
}
const selectEls = document.querySelectorAll("select");
selectEls.forEach((select) => {
select.addEventListener('change', changes);
});
const addDets = (ev) => {
ev.preventDefault();
let officials = {
name: document.getElementById("name").value,
age: document.getElementById("age").value,
favColor: selectedVal,
location: selectedVal
}
list.push(officials)
document.forms[0].reset();
console.log(list);
}
document.addEventListener("DOMContentLoaded", () => {
document.getElementById('btn').addEventListener('click', addDets);
});
<body>
<form action="" id="form">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="age">Age:</label>
<input type="number" name="age" id="age">
<select name="favorites" id="fav">
<option value="" selected disabled>Favorite Colors</option>
<option value="Red">R</option>
<option value="Blue">B</option>
<option value="Yellow">Y</option>
</select>
<select name="location" id="loc">
<option value="" selected disabled>Location</option>
<option value="L">L</option>
<option value="V">V</option>
<option value="M">M</option>
</select>
<button id="btn" type="submit">OK</button>
</form>
</body>
</html>
2
Answers
What’s going wrong:
You are using
selectedVal
to retrieve the values ofselect
elements. The issue here is that you are trying to store multiple values into a single variable. Thus, when you selectred
for example,selectedValue
will contain red and update bothfavColor
andlocation
with that value.Instead, you can simply retrieve their value the same way you retrieved the value of name and age.
keep in mind that this will return the value rather than the option, so if you pick the color
R
it will store the valueRed
.Working snippet:
Skip all the ids of the input elements and just use the name attribute. On the submit event the form is
ev.target
and then you can get all the values byev.target.[name].value
.An alternative could be to use FormData() for getting all values and then run through the entities.