Home > other >  How can I get the uncheked value from checkbox in React
How can I get the uncheked value from checkbox in React

Time:06-17

I have a simple Contact form when I check the checkbox I get true as a return value but when I don't I get an empty value. I've done some research but I got stuck.

Ps : SendEmail function works fine

How can I get a value from the input even when the checkbox is unchecked?

const [disabled, setDisabled] = useState(false);
const handleClick = () => setDisabled(!disabled);

<form ref={form}  onSubmit={sendEmail}>
          <div className="inputBox">
            <input type="text" name="user_name" placeholder="First & Last Name" required/>
          </div>

          <div className="inputBox">
            <input type="email" name="user_email" placeholder=" Email" required/>
          </div>

          <div className="inputBox">
            <textarea name="user_message" placeholder="Anything else we should know" rows="10" required></textarea>
          </div>

          <div className="checkbox-container">
            <input type="checkbox" id="scales" 
                  name="user_checkbox" disabled={handleClick} value={true}/>  
            <label for="user_checkbox">By submitting a request you acknowledge the requirement.</label>
          </div>

          <div className="inputBox">
            <input type="Submit"/>
          </div>
        </form>

Thank you

CodePudding user response:

The value for the checkbox is going to be boolean. True for checked. false for unchecked. What I did here. is to make a state with a false value and assigned that state to the checkbox value to make it unchecked. by using the onChange on the checkbox you will be able to change the state for the opposite of its value which will be the new value True.

import { useEffect, useState } from "react";

export default function App() {
  const [checkbox, setCheckbox] = useState(false);

  useEffect(() => {
    if (checkbox) console.log("true");
    else console.log("false");
  }, [checkbox]);

  return (
    <div className="App">
      <input
        type="checkbox"
        id="checkbox"
        value={checkbox}
        onChange={() => setCheckbox(!checkbox)}
      />
      <label htmlFor="checkbox">click</label>
    </div>
  );
}

inside the useEffect I made if condition for the true or false values that will come from that state depend on the checkbox. Also, I added the checkbox state to the useEffect dependency to re-render the component.

  • Related