Reputation: 95
I have problem with adding all selected values to the state (hooks). This is example of my code:
<div className="row">
<div className="input-field col s12">
<select multiple onChange={props.handleSelectedMultiple} id="balcony">
<option value="" disabled>
Brak
</option>
<option value="Balkon">Balkon</option>
<option value="Taras">Taras</option>
<option value="Ogród">Ogród</option>
<option value="Loggia">Loggia</option>
<option value="Taras na dachu">Taras na dachu</option>
</select>
<label>Balkon</label>
</div>
</div>
and function:
const handleSelectedMultiple = e => {
console.log(e.target.value);
};
The problem is that in console.log apears the value from FIRST SELECTED OPTION, so when I choose in this order Taras, Ogród, Loggia, in console i have (3)Taras. The goal is to add to state all selected values.
Anyone?
Upvotes: 0
Views: 2650
Reputation: 22895
You need to calculate the selected options. You can do something like
const handleSelectedMultiple = evt => {
const values = Array.from(evt.target.selectedOptions, option => option.value);
// Or this way
// const values = [...evt.target.selectedOptions].map(opt => opt.value)
console.log('values', values);
};
Upvotes: 2