Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from Multiple Checkbox to array in react?

How to get multiple checkbox values to an array in react js? This is my dynamic destination places from API. I want post to Backend with an array.

{
  this.state.destination.length > 0 ? (
    this.state.destination.map((destination, index) => (
      <div className="col-md-3">
        <div class="pretty p-default">
          <input type="checkbox" name="dest" value={index} onClick={event => this.handleDestination(event)} />
          <div class="state p-primary">
            <label>{destination.dest_name}</label>
          </div>
        </div>
      </div>
    ))
  ) : (
    <div>
      <label>
        <b>No results found ! </b>{' '}
      </label>
    </div>
  );
}



handleDestination(event) {

    const options=this.state.options
    let index
    if(event.target.checked){
      options.push(+event.target.value)
    }
    else{
      index=options.indexOf(+event.target.value)
      options.splice(index,1)
    }
    this.setState({ options:options})

}
like image 995
Gu Gue Avatar asked Jan 05 '18 05:01

Gu Gue


2 Answers

You can bind your handleDestination method with with an extra parameter - index of checked element: this.handleDestination.bind(this, index)

Worked example fiddle:

class Example extends React.Component {
  ...      
  onToggle(index, e){
    let newItems = this.state.items.slice();
    newItems[index].checked = !newItems[index].checked

    this.setState({ items: newItems })
  }

  render() {
    return (
        <div>
          <ul>
          {this.state.items.map((item, i) =>
            <li key={i}>
              {item.text}
              // binding an index
              <input type="checkbox" onChange={this.onToggle.bind(this, i)} />
            </li>
          )}
          </ul>
        <br/>
          // filter by checked element
          You checked: {JSON.stringify(this.state.items.filter(item => item.checked))}
        </div>
    )
  }
}

UPDATE For your code - change

this.handleDestination(event)

to

this.handleDestination.bind(this, index)
                   ^^^^^^^^^^^^^^^^^

Then modify a handleDestination method to similar what i did above:

handleDestination(index, event){
  console.log(index) // checked element index
  console.log(this.props.destination[index]) // your checked element
  ...
}

Hope it will help

like image 165
The Reason Avatar answered Oct 09 '22 02:10

The Reason


This is a similar pattern that i used in my project.You can reference here.

 state = {
    form: {
      companyType: '',
      services: [],
      name: '',
      surname: '',
      email: '',
      concepts: [],
      technologies: [],
    },
  };


public handleChange = (event: any) => {
    const { name } = event.target;
    const checkedArr = [];
    let value;
    if (event.target.type !== 'checkbox') {
      value = event.target.value;
    } else {
      const checkeds = document.getElementsByTagName('input');
      for (let i = 0; i < checkeds.length; i++) {
        if (checkeds[i].checked) {
          checkedArr.push(checkeds[i].value);
        }
      }
      value = checkedArr;
    }

    const { form } = this.state;
    form[name] = value;

    this.setState({ form });
  };

I'm getting checkbox values into arrays.

like image 20
isadev41 Avatar answered Oct 09 '22 03:10

isadev41