I'm trying to get the list of the selected options from the following form in React.
<form onSubmit={ this.handleOptionsSelected.bind(this) }>
<div>
<select multiple>
{ this.getOptionList() }
</select>
</div>
<input type="submit" value="Select"/>
</form>
Here is my handleOptionsSelected implementation.
handleOptionsSelected(event) {
event.preventDefault();
console.log("The selected options are " + event.target.value);
}
However, I got undefined value for event.target.value.
Does someone know how to correct the code above?
You can add a ref in your <select ref={node => this.select = node} multiple> and loop over the values.
Something like this.
class Example extends React.Component{
handleOptionsSelected(event){
event.preventDefault();
const selected = [];
for(let option of this.select.options){
if(option.selected){
selected.push(option.value)
}
}
console.log(selected);
}
render() {
return (
<form onSubmit={ this.handleOptionsSelected.bind(this) }>
<div>
<select ref={node => this.select = node} multiple="true">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</div>
<input type="submit" value="Select"/>
</form>
)
}
}
ReactDOM.render(
<Example name="World" />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With