mehdi parastar
mehdi parastar

Reputation: 827

Material ui multiple Select

this is my code : Code Sandbox

when I select an item from Select component; the value of

event.target.value

is undefined !!

What is proper implementation?

Upvotes: 14

Views: 50095

Answers (3)

Sumanth Madishetty
Sumanth Madishetty

Reputation: 3605

You need to pass a value prop to MenuItem

Please refer below code

  <TextField
    classes={{ root: classes.root }}
    select
    name="userRoles"
    id="userRoles"
    variant="outlined"
    label="userRoles"
    SelectProps={{
      multiple: true,
      value: formState.userRoles,
      onChange: handleFieldChange
    }}
  >
    <MenuItem value="admin">Admin</MenuItem>
    <MenuItem value="user1">User1</MenuItem>
    <MenuItem value="user2">User2</MenuItem>
  </TextField>

Please refer to this sandbox for example

Upvotes: 26

Sunil tc
Sunil tc

Reputation: 2612

You need to pass value for each option.

<MenuItem value="Admin">Admin</MenuItem>
<MenuItem value="User1">User1</MenuItem>
<MenuItem value="User2">User2</MenuItem>

Upvotes: 1

Jax-p
Jax-p

Reputation: 8593

As you can see in documentation of Multiple Select in MUI you have to iterate over each option and check if it is selected.

const handleChangeMultiple = event => {
    const { options } = event.target;
    const value = [];
    for (let i = 0, l = options.length; i < l; i += 1) {
      if (options[i].selected) {
        value.push(options[i].value);
      }
    }
    console.log(value); // selected options
};

Upvotes: 1

Related Questions