0

I have the following code with multiple select dropdown list. The handle change calls on selecting each value from the dropdown. How can i change this to call the handleChange function only after selecting the multiple values?

handleChange(e) {
    console.log(e.target.value);
}

render() {

    return(
        <select className="form-control" key="1" name="degree" onChange={this.handleChange} multiple>
            <option value="1" key="1">1</option>
            <option value="2" key="2">2</option>
            <option value="3" key="3">3</option>
            <option value="4" key="4">4</option>
            <option value="5" key="5">5</option>
        </select>
        )
}

Update: I need to get the array of selected values in the console is my basic requirement.

8
  • how do you know when the required value is selected, as apposed to any other value in the list? Commented Feb 20, 2018 at 9:13
  • I mean after selecting multiple values. Any event handlers there for doing this? Commented Feb 20, 2018 at 9:22
  • 1
    what do you mean by 'selecting the multiple values' in a dropdown? Commented Feb 20, 2018 at 9:22
  • So the condition is selectedValues > 1? Commented Feb 20, 2018 at 9:40
  • 1
    I believe you are looking for -> e.target.selectedOptions not a value Commented Feb 20, 2018 at 9:41

3 Answers 3

1

You could always use a fast fail in your action handler

handleChange(e) {
    const requiredValues = [3, 5]
    if (!requiredValues.includes(e.target.value) return
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is how I'd do it!
0

underscore provides a method called _.after(). This might suit your requirements.

Comments

0

You could do your "select" handler logic after you have multiple values.

One example would be storing the selected values in state and the handler would look like this :

onChangeHandler = (e) => {
  this.setState({ values } => {
    const newValues = values;
    const currentValue = e.target.value;

    const index = values.indexOf(currentValue);

    if (index > -1) {
      // Remove value
      newValues.splice(index, 1);
    } else {
      // Add value
      newValues.push(currentValue);
    }

    // You can do your logic here, before state is updated
    // if (newValues.length > 1) {
    // do multiple values logic
    // }

    // Update state
    return {
      values: newValues
    }
  }, () => {
    // You can do your logic here, after state is updated
    // if (this.state.values.length > 1) {
    // do multiple values logic
    // }
  })
}

Comments

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.