Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get options from multiple select form in React

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?

like image 984
hackjutsu Avatar asked Apr 01 '26 00:04

hackjutsu


1 Answers

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>
like image 181
QoP Avatar answered Apr 02 '26 14:04

QoP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!