Home > Software design >  Trigger "tick box" message in checkbox field
Trigger "tick box" message in checkbox field

Time:09-02

I am using React, and I would like to find a way to trigger this message (that now triggers only when pressing the type="submit" button, on will, is there any action I can use to trigger this message at any point (for example if a user presses any other button)

enter image description here

              <input
                id="conditions"
                type="checkbox"
                name="conditions"
                ref={acceptConditions}
                required
              ></input>

CodePudding user response:

This can be achieved with reportValidity() MDN documentation

setTimeout(() =>
  document.getElementById('example').reportValidity(), 
  3000
)
<input id="example" type="checkbox" required />

CodePudding user response:

Ok here are a few approaches, that works.

approach 1 Using the reportValidity()

This function will check the validity of the element and then trigger the event.

import { useRef } from "react";
import "./styles.css";

export default function App() {
  const acceptConditions = useRef();
  const formRef = useRef();
  const handleSubmit = () => {
    acceptConditions.current.reportValidity();
  };
  return (
    <form ref={formRef}>
      <input
        id="conditions"
        type="checkbox"
        name="conditions"
        ref={acceptConditions}
        required
      ></input>
      <span>Tick this box to continue</span>
      <br />
      <button type={"submit"}>submit the form</button>
      <br />
      <button onClick={handleSubmit}>Imposter button</button>
    </form>
  );
}

This is a good apporach And one that i recommend.

approach 2:

First of all if you want any other button to trigger the same event then you can do is make a reference to the form and then submit the form manually on the button press.

Here is an example.

import { useRef } from "react";
import "./styles.css";

export default function App() {
  const acceptConditions = useRef();
  const formRef = useRef();
  const handleSubmit = () => {
    console.log(formRef.current.submit);
  };
  return (
    <form ref={formRef}>
      <input
        id="conditions"
        type="checkbox"
        name="conditions"
        ref={acceptConditions}
        required
      ></input>
      <span>Tick this box to continue</span>
      <br />
      <button type={"submit"}>submit the form</button>
      <br />
      <button onClick={handleSubmit}>Imposter button</button>
    </form>
  );
}

in the above code the imposter button will trigger the same action as the button with the type="submit".

thank you.

  • Related