Retrieving value from <select> with multiple option in React

前端 未结 9 1316
无人共我
无人共我 2020-12-02 08:21

The React way to set which option is selected for a select box, is to set a special value prop on the

提交评论

  • 2020-12-02 09:04

    In the case you would like to keep track of the selected options while the form is being completed:

    handleChange(e) {
        // assuming you initialized the default state to hold selected values
        this.setState({
            selected:[].slice.call(e.target.selectedOptions).map(o => {
                return o.value;
            });
        });
    }
    

    selectedOptions is an array-like collection/list of elements related to the DOM. You get access to it in the event target object when selecting option values. Array.prototype.sliceand call allows us to create a copy of it for the new state. You could also access the values this way using a ref (in case you aren't capturing the event), which was another answer for the question.

    0 讨论(0)
  • 2020-12-02 09:10

    Easiest way...

    handleChange(evt) {
      this.setState({multiValue: [...evt.target.selectedOptions].map(o => o.value)}); 
    }
    
    0 讨论(0)
  • 2020-12-02 09:11

    The following worked for me

    var selectBoxObj = React.findDOMNode(this.refs.selectBox)
    var values = $(selectBoxObj).val()
    
    0 讨论(0)
  • 2020-12-02 09:15

    Try this one:

    dropdownChanged = (event) => {
        let obj = JSON.parse(event.target.value);
        this.setState(
            {
                key: obj.key,
                selectedName: obj.name,
                type: obj.type
            });
    }
    
    
    <select onChange={this.dropdownChanged} >
    <option value={JSON.stringify({ name: 'name', key: 'key', type: "ALL" })} >All Projetcs and Spaces</option></select>
    
    0 讨论(0)
  • 2020-12-02 09:17

    In case you want to use ref you can get selected values like this:

    var select = React.findDOMNode(this.refs.selectRef); 
    var values = [].filter.call(select.options, function (o) {
          return o.selected;
        }).map(function (o) {
          return o.value;
        });
    

    2018 ES6 update

      let select = this.refs.selectRef;
      let values = [].filter.call(select.options, o => o.selected).map(o => o.value);
    
    0 讨论(0)
  • 提交回复
    热议问题