Home > Enterprise >  react-hook-form not getting value, when value set based on select option value in reactjs
react-hook-form not getting value, when value set based on select option value in reactjs

Time:11-22

I am using react-hook-form validation for my project. I have a select option, when it change I set the value of selected one to another input which is customer but when I submit the form , customer value show empty, How to fix this issue ?

This is my code

function App() {
const [inputs, setInputs] = useState();
const [inputs1, setInputs1] = useState();

const {
register,
formState: { errors },
trigger,
handleSubmit
} = useForm({
defaultValues: {
  searchby: "searchby",
  customers: "",
  firstName: ""
  }
 });

const onSubmit = (data) => {
alert(JSON.stringify(data));
};

const handleInputChanges = (event) => {
const name = event.target.name;
const value = event.target.value;
 setInputs(value);
 setInputs1(value);
};

  return (
<form onSubmit={handleSubmit(onSubmit)}>
  <select
    name="searchby"
    {...register("searchby", {
      required: "password is required."
    })}
    value={inputs}
    onChange={handleInputChanges}
  >
    <option selected value="searchby">
      Search By
    </option>
    <option value="customerID">Custimer ID </option>
    <option value="teleco">Teleco</option>
  </select>
  {errors.searchby && <p>This field is Required</p>}
  <label>Customer: </label>
  <input
    name="customers"
    {...register("customers")}
    value={inputs1}
    onChange={handleInputChanges}
  />

  {errors.customers && <p>This field is Required</p>}

  <label>First name: </label>
  <input {...register("firstName", { required: true })} />
  {errors.firstName && <p>This field is Required</p>}

  <input type="submit" />
  <button
    type="button"
 
      >
    Validate All
     </button>
    </form>
  );
  }

This is what I am getting when I submit the form

enter image description here

Code link : Edit react-hook-form (forked)

  • Related