PDSSandeep
PDSSandeep

Reputation: 189

on select multiple check boxes get all values using ReactJs with BootstrapUI

Code below is to get selected values(Like a search refinement/search ). For Example, If I click on the Political Checkbox, I should get Political Value If I click on the MovieCheckbox, I should get MovieValue as well as Political Value If I uncheck It should display only selected checkbox value. Below is the code which I have written

class Refinments extends Component {
    render(){
    const { handleChange,handleClick } = this.props;
    return(
    <Form>
       {['checkbox'].map(type => (
            <div key={`Political`} className="mb-1">
              <Form.Check 
                type={type}
                custom 
                id={`Political}`}
                label={`Political`}
                value={`Political`}
                onChange={handleChange.bind(this, "Political")}
              />
            </div>
        ))}
        {['checkbox'].map(type => (
            <div key={`movies`} className="mb-1">
              <Form.Check 
            type={type} custom
            id={`movies}`}
            label={`Movies`}
            value={`Movies`}
             onChange={handleChange.bind(this, "Movies")}
              />
            </div>
        ))}
     </Form>
     )}

export default Refinments;

Upvotes: 0

Views: 371

Answers (1)

Dan Philip Bejoy
Dan Philip Bejoy

Reputation: 4381

The best option is to store the selected values in a state variable. handleChange method checks if the changed checkbox value is in the valArr, If it is present it removes the value from the array and replaces the state variable with the new array and if its not present it simply pushes the value into the array.

So this.state.valArr will always and only have the selected checkbox values.

constructor(props) {
  super(props);
  this.state = {
    valArr: []
  }
}
handleChange = (val) => {
  let { valArr } = this.state;
  let index = valArr.indexOf(val);
  if (index != -1)
      valArr.splice(index, 1);
  else
      valArr.push(val);
  this.setState({ valArr });
}
render() {
  .
  .
  .
  <div key={`movies`} className="mb-1">
      <Form.Check 
        type={type} custom
        id={`movies}`}
        label={`Movies`}
        value={`Movies`}
        onChange={this.handleChange}
      />
  </div>
}

Upvotes: 1

Related Questions