score:57

Accepted answer

With Array.from() and e.target.selectedOptions you can perform a controlled select-multiple:

handleChange = (e) => {
  let value = Array.from(e.target.selectedOptions, option => option.value);
  this.setState({values: value});
}

target.selectedOptions return a HTMLCollection

https://codepen.io/papawa/pen/XExeZY

score:0

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>

score:0

After spending a lot of time with this topic, and seeing that we are now all using mostly hooks and newbies may have never even dealt with classes in reactjs. I decided to update this answer so that people can easily deal with using vanilla javascript and ES6. I am also including a link to codesandbox so that people can play with the code and modify it to their application.

Here is the code, it has excessive console logs so that people can figure out what is doing what in the code and how it is doing it.

import "./styles.css"
import {useRef} from 'react'


export default function App() {

  const handleSubmit = async(e) => {
    e.preventDefault()
    let selected = [...recipeRef.current.options]
                .filter(option => option.selected)
                .map(option => option.value)
    console.log(new Date(), ' recipeType: ', selected)
    console.log(new Date(), 'with ref: ', [...recipeRef.current.options]);
    [...recipeRef.current.options].map(option => console.log(option,'; ',option.selected))
    console.log([...recipeRef.current.options].filter(option => option.selected))
    console.log([...recipeRef.current.options].filter(option=>option.selected).map(option => option.value))
  }
  const recipeRef = useRef()

  return (
    <div className="App">
      <h1>Hello CodeSandbox example for select Multiple by Julio Spinelli</h1>
      <form onSubmit={handleSubmit}>
          <div className="mb-6">
              <label htmlFor="text" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Name of the Recipe</label>
              <input type="text" id="text" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" required ></input>
          </div>
          <div className="mb-6">
              <label htmlFor="recipeType" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300">Recipe Type</label>
              {/* <input type="text" id="text" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" required onChange={(e)=>{setRecipeType(e.target.value)}} value={recipeType}></input> */}
              <select name="recipeType" id="recipeType" ref={recipeRef} multiple={true} size={3}> {/* Step 2 - Add the reference to `select` element */}
                <option value="unselected">unselected</option>
                <option value="Grill">Grill</option>
                <option value="Steak">Steak</option>
                <option value="Pizza">Pizza</option>
              </select>
          </div>
          <div className="flex items-start mb-6">
              <div className="flex items-center h-5">
              <input id="remember" aria-describedby="remember" type="checkbox" className="w-4 h-4 bg-gray-50 rounded border border-gray-300 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800" ></input>
              </div>
              <div className="ml-3 text-sm">
              <label htmlFor="remember" className="font-medium text-gray-900 dark:text-gray-300">Recipe uploaded?</label>
              </div>
          </div>
          <button type="submit" className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Save</button>
      </form>
    </div>
  )
}

score:1

Another way to do it:

handleChange({ target }) {
    this.props.someCallback(
       Array.prototype.slice.call(target.selectedOptions).map(o => o.value)
    )
}

score:3

The following worked for me

var selectBoxObj = React.findDOMNode(this.refs.selectBox)
var values = $(selectBoxObj).val()

score:7

You can actually find the selectedOptions inside the target... no need to iterate over all the options. Let's imagine you want to send the values to an onChange function passed to your component as props: you can use the following function on the onChange of your multiple select.

onSelectChange = (e) => {
    const values = [...e.target.selectedOptions].map(opt => opt.value);
    this.props.onChange(values);
  };

score:8

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.

score:11

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);

score:15

Easiest way...

handleChange(evt) {
  this.setState({multiValue: [...evt.target.selectedOptions].map(o => o.value)}); 
}

score:118

The same way you do anywhere else, since you're working with the real DOM node as the target of the change event:

handleChange: function(e) {
  var options = e.target.options;
  var value = [];
  for (var i = 0, l = options.length; i < l; i++) {
    if (options[i].selected) {
      value.push(options[i].value);
    }
  }
  this.props.someCallback(value);
}

Related Query

More Query from same tag