0

I am having a form, When I submit the data it is going to server and I displayed the data in a table.. In the Table I am having edit button, When clicked on Edit button, the data should bind to the Form. Here I am unable to bind the Inputs fields, but not the Radio and Checkboxes...

const Form = () => {
    const [data, setdata] = useState({
        "UserName" : "",
          "dropDown" :"",
          "gender" : "",
          "checking" :""
    })

    const [update, setUpdate] = useState([])

    const handleChange =(e)=>{
     
        if(e.target.name !=="gender" && e.target.name !=="checking"){
            setdata({...data,[e.target.name]:e.target.value});
        }else if(e.target.name ==="gender"){
                let allgenders = document.getElementsByName("gender");
                allgenders.forEach((allradio)=>{
                          if(allradio.checked){
                            setdata({...data,[e.target.name]:e.target.value});    
                          }
                })
        }else if(e.target.name ==="checking"){
                  let getallCheckboxes =[];
                  let allCheckboxes =document.getElementsByName("checking");
                  allCheckboxes.forEach((allchecks)=>{
                                if(allchecks.checked){
                                    getallCheckboxes.push(allchecks.value)
                                }
                  });
                  setdata({...data,[e.target.name]:getallCheckboxes});     
                  
        }

    }
    useEffect(() => {
        getAllData();
}, [])

   const handleSubmit=(e)=>{
    e.preventDefault();
    // setUpdate({...data,update});
    // console.log(data);
      axios.post('http://localhost:3000/users',data).then((res)=>{
        //   console.log("user added successfully");
        getAllData();
        handleClear();      
      })

   }

  const getAllData=()=>{
    axios.get('http://localhost:3000/users').then((res)=>{
        setUpdate(res.data);
       })
  }

const deleteUser=(dating)=>{
    console.log(dating);
    axios.delete('http://localhost:3000/users/'+dating.id).then(res=>{
        getAllData();
    })
}

This is the Funtions for Edit and update,Here I am able to bind the Inputs fields, but not the Radio and Checkboxes...

 const editUser=(userData)=>{
        setdata(userData)
    }
    
     const handleEdit=()=>{
         console.log(data);
             axios.put('http://localhost:3000/users/'+data.id,data).then(res=>{
            getAllData();
        })
     }
    
        return (
            <React.Fragment>
                <h1>LordShiva</h1>
                <div className="container mt-3">
                    <div className="row">
                        <div className="col-md-6">
                            <div className="card">
                                <div className="card-header bg-success text-white">
                                    <h4>Form</h4>
                                    <form>
                                        <div className="form-group">
                                            <input type="text" className="form-control" placeholder='UserName' name="UserName" value={data.UserName} onChange={handleChange} />
                                        </div>
                                        <div className="form-group">
                                            <input name="phone" className="form-control" placeholder='PhoneNumber' name="PhoneNumber" value={data.PhoneNumber} onChange={handleChange} />
                                        </div>
    
                                        <div className="form-group">
                                            <input name="email" className="form-control" placeholder='Email' value={data.email} onChange={handleChange} />
                                        </div>
                                        <div className="form-group">
                                            <select name="dropDown" value={data.dropDown} onChange={handleChange} className="form-control" >
                                                <option value=""></option>
                                                <option value="Reactjs">ReactJS</option>
                                                <option value="JS">JavaScript</option>
                                                <option value="csCSSs">CSS</option>
                                                <option value="HTML">HTML</option>
                                            </select>
                                        </div>
                                        <div class="form-row">
                                            <div className="form-group col-md-6">
                                                <label className="font-weight-bold">Gender : </label>
                                                <span className="font-weight-bold" > Male <input type="radio" name="gender" value={data.gender} onChange={handleChange}/></span>
                                                <span className="font-weight-bold" >  Female <input type="radio" name="gender" value={data.gender}  onChange={handleChange} /></span>
                                            </div>
                                            <div class="form-check col-md-6">
                                                
                                                        <label class="form-check-label" for="gridCheck">Course</label><br />
                                                <input type="checkbox" value="HTML" name="checking" value={data.checking} onChange={handleChange} /> HTML <br />
                                                <input type="checkbox" value="JavaScript" name="checking" value={data.checking} onChange={handleChange} /> JavaScript <br />
                                                <input type="checkbox" value="ReactJS" name="checking" value={data.checking} onChange={handleChange} /> ReactJS <br />
                                                <input type="checkbox" value="CSS" name="checking" value={data.checking} onChange={handleChange} /> CSS <br />
                                                    
                                            </div>
                                            <div className="form-row">
                                            <button className="btn btn-cyan" type="button" onClick={handleSubmit}>Submit</button>
                                            <button className="btn btn-cyan" type="button" onClick={handleEdit}>UpdateData</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div className="col-md-12">
                            <div className="card mt-5">
                                <div className="card-header blue-gradient text-white">
                                    <h4>FormDetails</h4>
                                    <div>
                                       <div className="row mt-3">
                                           <div className="col">
                                               <div className="table table-hover table-striped text-center table-primary">
                                                    <thead className="bg-dark text-white font-weight-bold">
                                                        <tr>
                                                            <th>UserName</th>
                                                            <th>DropDownValue</th>
                                                            <th>Gender</th>
                                                            <th>CheckboxValue</th>
                                                            <th>EDIT</th>
                                                            <th>DELETE</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                          {
                                                              update.map(emp => {
                                                                  return(
                                                                      <tr>
                                                                        <td>{emp.UserName} </td>
                                                                        <td>{emp.gender}</td>
                                                                        <td>{emp.checking}</td>
                                                                  <td><button className="btn btn-cyan font-weight-bold" onClick={()=>{editUser(emp)}}>Edit</button></td>  
                                                                        <td><button className="btn btn-green font-weight-bold" onClick={()=>{deleteUser(emp)}}>Delete</button></td>  
                                                                      </tr>
                                                                  )
                                                              })
                                                          }
                                                    </tbody>
                                               </div>
                                           </div>
                                       </div>
                                      
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </React.Fragment >
        )
    }

1 Answer 1

2

Change state to

const [data, setdata] = useState({
  UserName: "",
  dropDown: "",
  gender: null,
  checking: []
});

Update the handler to access the radio and checkbox id attributes

const handleChange = (e) => {
  if (e.target.name !== "gender" && e.target.name !== "checking") {
    setdata({ ...data, [e.target.name]: e.target.value });
  } else if (e.target.name === "gender") {
    let allgenders = document.getElementsByName("gender");
    allgenders.forEach((allradio) => {
      if (allradio.checked) {
        setdata({ ...data, [e.target.name]: e.target.id }); // <-- grab input id
      }
    });
  } else if (e.target.name === "checking") {
    let getallCheckboxes = [];
    let allCheckboxes = document.getElementsByName("checking");
    allCheckboxes.forEach((allchecks) => {
      if (allchecks.checked) {
        getallCheckboxes.push(allchecks.id); // <-- grab checkbox id
      }
    });
    setdata({ ...data, [e.target.name]: getallCheckboxes });
  }
};

Update/add handleClear to reset the state

handleClear = () => {
  setdata({
    UserName: "",
    dropDown: "",
    gender: null,
    checking: []
  });
};

Add id properties and change the value prop to checked and pass a boolean value

<label className="font-weight-bold">Gender : </label>
<span className="font-weight-bold">
  <label>
    Male
    <input
      id="male"
      type="radio"
      name="gender"
      checked={data.gender === "male"}
      onChange={handleChange}
    />
  </label>
</span>
<span className="font-weight-bold">
  <label>
    Female
    <input
      id="female"
      type="radio"
      name="gender"
      checked={data.gender === "female"}
      onChange={handleChange}
    />
  </label>
</span>

...

<label class="form-check-label" for="gridCheck">
  Course
</label>
<br />
<label>
  <input
    id="HTML"
    type="checkbox"
    name="checking"
    checked={data.checking.includes("HTML")}
    onChange={handleChange}
  />
  HTML
</label>
<br />
<label>
  <input
    id="JavaScript"
    type="checkbox"
    name="checking"
    checked={data.checking.includes("JavaScript")}
    onChange={handleChange}
  />
  JavaScript
</label>
<br />
<label>
  <input
    id="ReactJS"
    type="checkbox"
    name="checking"
    checked={data.checking.includes("ReactJS")}
    onChange={handleChange}
  />
  ReactJS
</label>
<br />
<label>
  <input
    id="CSS"
    type="checkbox"
    name="checking"
    checked={data.checking.includes("CSS")}
    onChange={handleChange}
  />
  CSS
</label>

Edit unable-to-bind-the-radio-button-and-checkbox-data-on-button-click-in-react-hooks

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.