Home > Net >  Checkbox value undefined
Checkbox value undefined

Time:09-02

Hello guys i have a problem, i have a 2 checkbox, each of them have value. The first checkbox is Any/Not, and the second one is Valid/Invalid. If the checkbox is checked the value will change to Any, if not checked the value will be not, same for the valid/invalid one.

I already tried, but when the checkbox is unchecked the value im getting is undefined. Btw i use react, node, and mysql. But the value is succesfully changed when the box is checked.

Here is the result from database :

Here is the code :

FormDataProvider.js

import React from 'react';
import {createContext, useState} from "react"
export const FormData = createContext();
export default function FormDataProvider({children}) {
    const [formData , setFormData] = useState({
        cName : "",
        Address : "",
        phoneNumber : "",
        presidentName : "",
        managerEmail : "",
        managerPhone : "",
        picEmail : "",
        picPhone : "",
        date: "",
        mainBusiness : "",
        employeeNumber : "",
        numberOfCustomer : "",
        myFile : "",
        any : "" ,
        valid : ""
      });
  return (
    <FormData.Provider value={{ formData, setFormData }}>
     {children}
    </FormData.Provider>
  );
}

Form.js

const Form = () => {

    let navigate = useNavigate();

    Axios.defaults.withCredentials = true;
  

    const { emailLog, setEmailLog } = useContext(EmailUser);
    const { loginStatus, setLoginStatus } = useContext(LoginStatus);
    const { formData , setFormData} = useContext(FormData);


  
    const handleChange = event => {
      if (event.target.checked) {
        setFormData({...formData, any : event.target.checked})
      } else {
        setFormData({...formData, any : "Not"})
      }
    };

    const handleChange2 = event => {
      if (event.target.checked) {
        setFormData({...formData, valid : event.target.checked})
      } else {
        setFormData({...formData, valid : "Invalid"})
      }
    };

   
   
  return (
    <form method='POST' encType='multipart/form-data' action='http://localhost:3001/registration'>
    <div className=''>
      <input className='inputForm' type='email' value={emailLog} name='email' required onChange={(e) => {
        setEmailLog(e.target.value) }} />
      <input className='inputForm' type='text' placeholder='Company Name' name="CompanyName" required value={formData.cName}  onChange={(event) =>
          setFormData({ ...formData, cName: event.target.value })}/>
      <input className='inputForm' type='text' placeholder='Address' name="Address" required value={formData.Address} onChange={(event) =>
          setFormData({ ...formData, Address: event.target.value })}  />
      <input className='inputForm' type='tel' placeholder='Phone Number' name="Phone" required value={formData.phoneNumber} onChange={(event) =>
          setFormData({ ...formData, phoneNumber: event.target.value })}  />
      <input className='inputForm' type='text' placeholder='President Director Name' name="PresidentName" required value={formData.presidentName} onChange={(event) => 
          setFormData({...formData, presidentName: event.target.value})} />
      <input className='inputForm' type='email' placeholder='Manager Email' name="ManagerEmail" required value={formData.managerEmail} onChange={(event) => 
          setFormData({...formData, managerEmail: event.target.value})}  />
      <input className='inputForm' type='tel'  placeholder='Manager Phone' name="ManagerPhone" required value={formData.managerPhone} onChange={(event) => 
          setFormData({...formData, managerPhone: event.target.value})} />
      <input className='inputForm' type='email'  placeholder='PIC Email' name="PICEmail" required value={formData.picEmail} onChange={(event) => 
          setFormData({...formData, picEmail: event.target.value})} />
      <input className='inputForm' type='tel'  placeholder='PIC Phone' name="PICPhone" required value={formData.picPhone} onChange={(event) => 
          setFormData({...formData, picPhone: event.target.value})} />
      <input className='inputForm' type='date'  placeholder='Date' name="EstablishedDate" required value={formData.date} onChange={(event) => 
          setFormData({...formData, date: event.target.value})} />
        <select className='selectBox' name='ChoiceBusiness' required onChange={(event) =>
          setFormData({...formData, mainBusiness: event.target.value})} >
                  <option value="" disabled selected hidden>Choose Main Business...</option>
                  <option value="Software License">Software License</option>
                  <option value="IT Services & Consulting">IT Services & Consulting</option>
                  <option value="IT Outsourcing">IT Outsourcing</option>
                  <option value="Hardware">Hardware</option>
                  <option value="General Trading">General Trading</option>
                  <option value="Others">Others</option>
        </select>
        <select className='selectBox' name='EmployeeNumber' required onChange={(event) =>
          setFormData({...formData, employeeNumber: event.target.value})} >
            <option value="" disabled selected hidden>Choose Employee Number...</option>
                <option value="1-50">1-50</option>
                <option value="51-100">51-100</option>
                <option value="101-250">101-250</option>
                <option value="251-500">251-500</option>
                <option value="500 ">500 </option>
        </select>
      <input className='inputForm' type="number"  placeholder='Number of Customer' name="NumberOfCustomer" required value={formData.numberOfCustomer} onChange={(event) => 
          setFormData({...formData, numberOfCustomer: event.target.value})} />

      <input className='inputFormDate' type="file" name='pdfFiles' multiple required onChange={(event) => 
          setFormData({...formData, myFile : event.target.value})}  />


        <div className='formCheckboxes'>
          <div className='formCheckbox'>
              <p>SK Menhum & Akta Notaris</p>
             
             

          <div >
              <input  type="checkbox" value="Any"  name="Any" onChange={handleChange}/>
              <label  for="inlineCheckbox1">Any</label>
          </div>
          <div >
              <input  type="checkbox" value="Valid"  name="Valid" onChange={handleChange2}/>
              <label  for="inlineCheckbox2">Valid</label>
          </div>
        
                      
        </div>
 </div>
          
          <button className='btnSubmit' type='submit'> Submit</button>
    </div>
    </form>
  )
}


export default Form

CodePudding user response:

  1. Always use the functional update format to update state based on its previous value to prevent loss of batched state updates.
  2. When checked, you're setting the value to the checked property which is a Boolean. You want the value property instead

Try something like this

setFormData((fd) => ({
  ...fd,
  any: event.target.checked ? event.target.value : "Not",
}));

You could probably use something generic for all inputs provided their name attributes match the object keys you want.

Checkboxes could provide their off value in a data-attribute, eg

<input
  
  type="checkbox"
  value="Any"
  data-off="None"
  name="any"
  onChange={handleChange}
/>
// generic handler for all inputs
const handleChange = (e) => {
  let value;
  switch (e.target.type) {
    case "checkbox":
      value = e.target.checked ? e.target.value : e.target.dataset.off;
      break;
    case "file":
      value = e.target.files[0];
      break;
    default:
      value = e.target.value;
  }

  setFormData((fd) => ({
    ...fd,
    [e.target.name]: value,
  }));
};
  • Related