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
Aucun commentaire:
Enregistrer un commentaire