5

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})

}
1

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

I gotcha my new function is like that .It works well. but the value is not coming out, the index of array is coming .How can I change .this is my new function
I updated my question again .Let me check above my handleDestination function.I do not want to get index of array, I want value . HOw can I fix that
@GuGue Have you looked at my worked example? I updated my answer
1

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.

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.