skip to Main Content

enter image description here

When I submit how to get all checkbox state and notes using useState in hooks

function handleEditformsubmit(e: any) {
e.preventDefault();
var errids = [];

var arr_length = InspectionList.length;
var chkbx = "chkbx_";
var notes = "notes_";
var data = []; 

for (var i = 1; i <= arr_length; i++) {
let chkbx_state: any = (document.getElementById(chkbx + i) as HTMLInputElement).checked;
let user_note: any = (
document.getElementById(notes + i) as HTMLInputElement
)?.value;
if (!chkbx_state && !user_note){
document.getElementById(notes + i)
console.log(notes+i)
errids.push(notes+i)
setErrId(errids)
}
let row_data = Object();
row_data["id"] = i;
row_data["is_checked"] = chkbx_state;
row_data["notes"] = user_note;
data.push(row_data);
}
setInsData(data)
errids = []
}

This is working fine, but I would like to learn How to solve using states. Any advise please thanks

2

Answers


  1. import React, { useState } from 'react';
    
    function YourComponent() {
      const [inspectionList, setInspectionList] = useState([
        // Initialize your InspectionList here
        // Example: { id: 1, isChecked: false, notes: '' },
        // Add similar objects for each item in your list
      ]);
    
      const [errIds, setErrIds] = useState([]);
    
      const handleCheckboxChange = (id) => {
        const updatedList = inspectionList.map((item) =>
          item.id === id ? { ...item, isChecked: !item.isChecked } : item
        );
        setInspectionList(updatedList);
      };
    
      const handleNoteChange = (id, value) => {
        const updatedList = inspectionList.map((item) =>
          item.id === id ? { ...item, notes: value } : item
        );
        setInspectionList(updatedList);
      };
    
      const handleEditFormSubmit = (e) => {
        e.preventDefault();
        const errIds = [];
    
        for (const item of inspectionList) {
          if (!item.isChecked && !item.notes) {
            errIds.push(item.id);
          }
        }
    
        setErrIds(errIds);
    
        // You can also set the updated inspection data here
        // setInsData(inspectionList);
    
        // Clear errIds
        setErrIds([]);
      };
    
      return (
        <div>
          <form onSubmit={handleEditFormSubmit}>
            {inspectionList.map((item) => (
              <div key={item.id}>
                <input
                  type="checkbox"
                  checked={item.isChecked}
                  onChange={() => handleCheckboxChange(item.id)}
                />
                <input
                  type="text"
                  value={item.notes}
                  onChange={(e) => handleNoteChange(item.id, e.target.value)}
                />
              </div>
            ))}
            <button type="submit">Submit</button>
          </form>
          {errIds.length > 0 && (
            <div>
              Errors: {errIds.map((id) => <span key={id}>{id}, </span>)}
            </div>
          )}
        </div>
      );
    }
    
    export default YourComponent;

    In this code:

    We maintain the state of your inspection list using useState.
    We use handleCheckboxChange and handleNoteChange functions to update the state when a checkbox or note input changes.
    In handleEditFormSubmit, we iterate over the list to check for errors, and we set errIds accordingly.
    Finally, we use the state variables to display the checkboxes, notes, and error messages in the component’s JSX.

    Login or Signup to reply.
  2. import React from "react";
    import { useState } from "react";
    
    const arr = [
      {
         id: 1,
         name: "John Doe",
      },
      {
         id: 2,
         name: "Mark A",
      },
      {
         id: 3,
         name: "Triple H",
      },
    ];
    
    
    const CheckBoxSelect = () => {
    const [errIds, setErrIds] = useState([]);
    const [isChecked, setIsChecked] = useState(false);
    
    const handleCheckBox = () => {
      setIsChecked(!isChecked);
    };
    
    const handleIndex = (id) => {
       if (errIds?.includes(id)) {
          setErrIds((prevNum) => prevNum.filter((num) => num !== id));
        }  else {
           setErrIds((prev) => [...prev, id]);
        }
      };
    
    console.log("Stored Data: ", errIds);
    
    
     return (
    
    
     <div>
      {arr &&
        arr.map((i) => (
          <div key={i.id}>
            <div>
              <input
                onChange={() => handleCheckBox(i.id)}
                type="checkbox"
                checked={errIds.includes(i.id) ? true : false}
                id="checkbox"
              />
              <label
                onClick={() => handleIndex(i.id)}
                htmlFor="checkbox"
              ></label>
            </div>
            <div>
              <p>{i.name}</p>
            </div>
          </div>
        ))}
    </div>
     );
    };
    
    export default CheckBoxSelect;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search