1

I want to console.log an array of the checkboxes that are checked. Like if checkbox 1, 2, and 5 are checked, I want it to show in the console as an array of each checkbox's value. I can get the last value selected to show up in the console, but I can't get an array of all the checkboxes checked to show up. They just show up separate.

import { CheckboxData } from "../../../Data/SurveyData";

class CheckboxForm extends Component {
  constructor(props) {
    super(props);
    this.state = { value: [] };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
    console.log("Checkbox: ", event.target.value);
  }

  handleSubmit(event) {
    event.preventDefault();
  }

  render() {
    return (
      <div
        id="checkboxContainer"
        className="container"
        onSubmit={this.handleSubmit}
      >
        {CheckboxData.map((data, key) => {
          return (
            <div key={key}>
              <h5>{data.question}</h5>
              <div className="form-check">
                <input
                  className="form-check-input "
                  required={data.required}
                  name={data.name}
                  type={data.type}
                  value={data.options[0].value}
                  id={`${data.options[0].name}-${key}`}
                  onChange={this.handleChange}
                />
                <label
                  className="form-check-label "
                  htmlFor={`${data.name}-${key}`}
                >
                  {data.options[0].label}
                </label>
              </div>
              <div className="form-check">
                <input
                  className="form-check-input "
                  required={data.required}
                  name={data.name}
                  type={data.type}
                  value={data.options[1].value}
                  id={`${data.options[1].name}-${key}`}
                  onChange={this.handleChange}
                />
                <label
                  className="form-check-label "
                  htmlFor={`${data.name}-${key}`}
                >
                  {data.options[1].label}
                </label>
              </div>
              <div className="form-check">
                <input
                  className="form-check-input "
                  required={data.required}
                  name={data.name}
                  type={data.type}
                  value={data.options[2].value}
                  id={`${data.options[2].name}-${key}`}
                  onChange={this.handleChange}
                />
                <label
                  className="form-check-label "
                  htmlFor={`${data.name}-${key}`}
                >
                  {data.options[2].label}
                </label>
              </div>
              <div className="form-check">
                <input
                  className="form-check-input "
                  required={data.required}
                  name={data.name}
                  type={data.type}
                  value={data.options[3].value}
                  id={`${data.options[3].name}-${key}`}
                  onChange={this.handleChange}
                />
                <label
                  className="form-check-label "
                  htmlFor={`${data.name}-${key}`}
                >
                  {data.options[3].label}
                </label>
              </div>
              <div className="form-check">
                <input
                  className="form-check-input "
                  required={data.required}
                  name={data.name}
                  type={data.type}
                  value={data.options[4].value}
                  id={`${data.options[4].name}-${key}`}
                  onChange={this.handleChange}
                />
                <label
                  className="form-check-label "
                  htmlFor={`${data.name}-${key}`}
                >
                  {data.options[4].label}
                </label>
              </div>
            </div>
          );
        })}
      </div>
    );
  }
}

export default CheckboxForm;

The data is in the SurveyData.js file as follows:

  {
    page: 2,
    name: "checkbox",
    question: "Check all that apply. I understand:",
    type: "checkbox",
    options: [
      {
        name: "checkbox1",
        value: "I am entering into a new contract.",
        label: "I am entering into a new contract.",
      },
      {
        name: "checkbox2",
        value:
          "I will be responsible for $49.95 each month until my contract is over.",
        label:
          "I will be responsible for $49.95 each month until my contract is over.",
      },
      {
        name: "checkbox3",
        value: "I have three days to cancel.",
        label: "I have three days to cancel.",
      },
      {
        name: "checkbox4",
        value:
          "If I cancel after three days, I will be responsible for the remainder of the contract.",
        label:
          "If I cancel after three days, I will be responsible for the remainder of the contract.",
      },
      {
        name: "checkbox5",
        value:
          "My system is monitored and if it is set off, the cops will come to my home.",
        label:
          "My system is monitored and if it is set off, the cops will come to my home.",
      },
    ],
  },
];```
5
  • You're assigning strings to checkbox values, which is odd. Commented Aug 21, 2020 at 22:29
  • The checkbox form should hold the state of all of the checkboxes, not just one single one. This might be a case of making a CheckBox component with its own onChange handler, with the CheckBoxForm component keeping track of the array of checked boxes with a handler passed down through props. Commented Aug 21, 2020 at 22:35
  • @MattDale I'm fairly new to react and don't quite understand what you mean. Can you explain, please? Commented Aug 21, 2020 at 22:37
  • @Cehhiro I had numbers for values, but my goal is to save the data and be able to recall it and I couldn't tell what I was saving when it was numbers. Commented Aug 21, 2020 at 22:39
  • @Heather You might first need to get a solid grasp on states, props, and components before you build something more complex. Otherwise, you might struggle unnecessarily on something that's straightforward once you handle these concepts. Commented Aug 21, 2020 at 22:40

1 Answer 1

1

You can change your handleChange function to update the array (this.state.value) rather than just logging the user input value. Then in the callback for this.setState you can log out all the values in the array.

The code below will see if the value already exists in your array; if it does exist, it removes it, otherwise it adds the value to the array

  handleChange(event) {
    const input = event.target.value;
    this.setState(
      {
        value: this.state.value.includes(input)
          ? this.state.value.filter((item) => item !== input)
          : [...this.state.value, input]
      },
      () => {
        console.log(this.state.value);
      }
    );
  }

Something else that might make things easier, is to check out react-hook-form or maybe Formik (which I thought was way more difficult to learn than hook form). Those libs will manage all this form state for you though, so you don't have to worry about it.

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

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.