bunty93 bunty93 - 1 month ago 22
React JSX Question

How to get multiple selected options value in React JS?

<Multiselect label='Select College' ref="collegeList" onChange={this.handleChange} multiple >
<option value='college1'>college1</option>
<option value='college2'>college2</option>
</Multiselect>


This component is from https://github.com/skratchdot/react-bootstrap-multiselect

What should be written inside the handleChange() function ?

Answer

Unfortunately, react-bootstrap-multiselect doesn't seem to expose any sort of API for getting the currently selected items, so you'll have to query them from the DOM directly. Try something like this:

handleChange: function () {
    var node = React.findDOMNode(this.refs.collegeList);
    var options = [].slice.call(node.querySelectorAll('option'));
    var selected = options.filter(function (option) {
        return option.selected;
    });
    var selectedValues = selected.map(function (option) {
        return option.value;
    });

    console.log(selectedValues);
}

If you're using jQuery, this can be simplified a bit to:

handleChange: function () {
    var node = $(React.findDOMNode(this.refs.collegeList));
    var selectedValues = node.children('option:selected').map(function(option) {
        return option.value;
    });

    console.log(selectedValues);
}
Comments