user16496326
user16496326

Reputation:

Push the Checkbox Value and Name in Array in React JS

I've issues with the checkbox. I want to get the value and name field data in array format to do further processes.

Here's Checkbox:

<input type="checkbox" id="Honda" name="A1" value="Honda" onClick={CheckHandler} /> 
<label htmlFor="Honda" >Honda</label>

Now, I want to get the name and value field data in JSON or in an array

Like this:

{ name:"A1", value:"Honda" }   //I want this.

So, I've coded like this:

import React, { Fragment, useState, useEffect } from "react";

export default function App() {
  const [cars, setCars] = useState([]);


  const CheckHandler = (e) => {

    const value = e.target.value;
    const name = e.target.name;

  //  setCars((prev) =>
  //    cars.includes(value)
  //      ? prev.filter((cur) => cur !== value)
  //      : [...prev, {[e.target.value]:`${e.target.name}`}] 
  //  );
  };

  useEffect(() => {
    console.log(cars);
  }, [cars]);

  return (
    <Fragment>
      <input type="checkbox" id="Honda" name="A1" value="Honda" onClick={CheckHandler}/>
      <label htmlFor="Honda">Honda</label>
      <br/>

      <input type="checkbox" id="Mustang" name="A8" value="Mustang" onClick={CheckHandler}/>
      <label htmlFor="Mustang">Mustang</label>
      <br />

      <input type="checkbox" id="Jeep" name="A12" value="Jeep" onClick={CheckHandler}/>
      <label htmlFor="Jeep">Jeep</label>
      <br />
    </Fragment>
  );
}

MY PROBLEM: whenever I Tick on checkbox It works fine, But when I unchecked its not returning sets from remaining items. IT's returning from all items. why ??

Any one Knows Answer ??

Sandbox https://codesandbox.io/s/late-water-piszn

Upvotes: 0

Views: 303

Answers (2)

halilcakar
halilcakar

Reputation: 1648

Hi I fiddled a bit of your code and

const checkHandler = (e) => {
  const value = e.target.value;
  const name = e.target.name;
  setCars((prev) =>
    cars.find(ch => ch[value] === name)
      ? prev.filter((cur) => cur[value] !== name)
      : [...prev, { [e.target.value]: `${e.target.name}` }]
  );
};

update your method like this and it's working.

Upvotes: 2

Soumya
Soumya

Reputation: 146

Here is the updated function I made for you answer

const CheckHandler = (e) => {
    console.log(cars);
    const value = e.target.value;
    const name = e.target.name;
    var found = false;
    for (var i = 0; i < cars.length; i++) {
      if (cars[i][value] === name) {
        found = true;
        break;
      }
    }
    setCars((prev) =>
      found
        ? prev.filter((cur) => cur[value] !== name)
        : [...prev, { [value]: name }]
    );
  };

Here is the sandbox

Upvotes: 0

Related Questions