3

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?

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It seems the <form> is not necessary here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.