Home > OS >  Need to get values from checkbox and validate that at least one is checked and save the values in a
Need to get values from checkbox and validate that at least one is checked and save the values in a

Time:07-13

so we have a form where we are asking a question where the user is able to submit multiple answers in a check box format, what im doing is using useState to hold the answers to the question, then validating the size of the array to set the button either disabled or not. Currently you have to check and uncheck an answer for it to even appear in the array and checking it multitple times still adds the same answer over and over again in the array instead of deleting it not sure what im doing wrong here.

Here is what happens when i click an option or multiple
enter image description here

Here is the entire file


function CoverageTime(props) {

  const navigate = useNavigate();
  const [isButtonDisabled, setIsButtonDisabled] = useState(true);
  const [coverageTime, setCoverageTime] = useState([]);


  

  function onChange(e) {

    const isChecked = e.target.checked;
    if (isChecked) {
      setCoverageTime(arr => [...arr, e.target.value]);
    }
    else {
    
      let index = coverageTime.indexOf(e.target.value);
      coverageTime.splice(index, 1);
      setCoverageTime(coverageTime)
    }

    checkSize()
    console.log(coverageTime)
  };

  function checkSize() {

    let value = coverageTime;
    if (coverageTime.length === 0) {
      toast.error('Please Select At Least One Coverage Time');
      setIsButtonDisabled(true);
    }
    if (coverageTime === "" || coverageTime === null || coverageTime === undefined) {
      toast.error('Please Select At Least One Coverage Time');
      setIsButtonDisabled(true);
    }

  }

  function nextStep(e) {
   
    e.preventDefault();
    console.log('final ', coverageTime)
    if (coverageTime.length === 0) {
      toast.error('Please Select At Least One Coverage Time');
      setIsButtonDisabled(true);
    }
    if (coverageTime === "" || coverageTime === null || coverageTime === undefined) {
      toast.error('Please Select At Least One Coverage Time');
      setIsButtonDisabled(true);
    }
    else {
      setIsButtonDisabled(false);
      navigate('/form/coverage-time-2');
    }
    
  }


  let checkBoxes = [
    {
      title: "I want to cover my burial expense",
      id: "burial_expense",
      value: "burial_expense",
    },
    {
      title: "I want to cover my mortgage",
      id: "mortgage",
      value: "mortgage",
    },
    {
      title: "I'm planning for retirement",
      id: "retirement",
      value: "retirement",
    },
    { title: "I want to leave a legacy", id: "legacy", value: "legacy" },
    {
      title: "I have health concerns",
      id: "health_concern",
      value: "health_concern",
    },
    {
      title: "I want to invest my money",
      id: "investments",
      value: "investments",
    },
    {
      title: "I want to support my spouse",
      id: "support_spouse",
      value: "support_spouse",
    },
    {
      title: "I want to support my children",
      id: "support_children",
      value: "support_children",
    },

  ]

return (
<div className="bg-[#F3F5FF] ">
<ToastContainer limit={1} autoClose={3000} closeOnClick={true} pauseOnFocusLoss={false} position="top-center" theme="colored" />

    <div className="formArea flex items-center justify-center py-5 px-4 sm:px-6 lg:px-4">
      <div className="max-w-lg w-full space-y-8">
        <div>
          <h2 className="mt-4 text-center text-4xl font-extrabold text-gray-900">
            Tell us about yourself
          </h2>
          <p className="text-center text-md font-medium text-gray-500">
            Select All That Apply
          </p>
        </div>
        <form className="mt-8 space-y-6">
          <div className="w-full space-y-6 relative flex justify-center leading-5">
              <div className=" leading-5 buttonBlock">
              {checkBoxes.map((checkBox) => (
                   <div className="relative flex items-start py-4">
                   <div className="ml-3 flex items-center h-5">
                     <input
                       id={checkBox.id}
                       name={checkBox.id}
                       type="checkbox"
                       className="focus:ring-blue-500 h-6 w-6 text-blue-600 border-gray-300 rounded mr-5"

                      onChange={onChange}
                     />
                     <label className="font-medium text-md text-gray-600">
                       {checkBox.title}
                     </label>
                   </div>
                 </div>
         
                ))}

            </div>
          </div>
          <button
                                type="submit"
                                disabled={isButtonDisabled}
                                className={`px-6 py-4 w-full  ${isButtonDisabled ? 'cursor-not-allowed disabled:opacity-75 bg-gray-500' : ""} ripple-bg-blue-200 text-lg bg-blue-400 hover:shadow-lg hover:shadow-blue-300/50 text-white rounded transition duration-200 zipSubmit  items-center align-middle flex flex-row text-center justify-center`}
                                id='address'
                                onClick={nextStep}

                            >
                                Next
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    className="h-6 w-auto pl-5"
                                    fill="none"
                                    viewBox="0 0 24 24"
                                    stroke="currentColor"
                                    strokeWidth={2}

                                >
                                    <path
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                        d="M13 7l5 5m0 0l-5 5m5-5H6"
                                    />
                                </svg>
                            </button>

          <LinkWithQuery to="/">Back</LinkWithQuery>
        </form>
      </div>
    </div>
    <BottomPhone />
</div>

  )
  
}
export default CoverageTime;

CodePudding user response:

you should pass value prop to input like you did for id,name,type and other props

<input
   id={checkBox.id}
   name={checkBox.id}
   type="checkbox"
   value={checkBox.value}
   className="focus:ring-blue-500 h-6 w-6 text-blue-600 border-gray-300 rounded mr-5"
   onChange={onChange}
/>

CodePudding user response:

just replace your checkboax input to below snipet there actual prob is you forget to add value={checkBox.id}.

<input
    id={checkBox.id}
    name={checkBox.id}
    type="checkbox"
    className="focus:ring-blue-500 h-6 w-6 text-blue-600 border-gray-300 rounded mr-5"
    onChange={onChange}
    value={checkBox.id}
/>
  • Related