Stop select input from triggering a forms onBlur

130 Views Asked by At

I have a form with two inputs, a text input and a select input. The text input is for city and the select input is for the state. The form onBlur is set to hide the form effectively cancelling the form input. However, when the select input is clicked the form onBlur is being called. Is there anyway to stop this from happening or a better way to cancel a form input and hide it? The app is a React app, the components are Flowbite React components, and styling is Tailwind Css.

{editingLocation && (
              <form
                className="flex-row justify center mb-4 -mt-2"
                onBlur={cancelEdit}
              >
                {" "}
                <div className="flex flex-row w-full items-center gap-2 scale-75 justify-center">
                  <TextInput
                    autoFocus
                    className="w-fit"
                    id="city"
                    placeholder="city"
                    shadow
                  ></TextInput>
                  <SelectInput options={STATES_LIST} />
                </div>{" "}
              </form>
            )}

I haven't really been able to try anything as the components are Flowbite React components and I can't go and modify node_modules. I have tried searching for possible solutions but I haven't found any questions that are similar to mine.

1

There are 1 best solutions below

0
On

I still don't get the idea, but using the blur event seams not fitting. If you would like the user to fill in the form (both input and select) you can set the required attribute on both. And then on the input event you can test if the form is valid, and is so disable both form fields (here I use a fieldset to do that) and then style the elements to disappear.

document.forms.form01.addEventListener('input', e => {
  if (e.target.form.reportValidity()) {
    e.target.form.citystate.disabled = true;
  }
});

document.forms.form01.addEventListener('invalid', e => {
  e.preventDefault();
}, true);
fieldset:disabled {
  display: none;
}
<form name="form01">
  <fieldset name="citystate">
    <input name="city" placeholder="city" required>
    <select name="state" required>
      <option value="">Select a state</option>
      <option value="1">State 1</option>
      <option value="2">State 2</option>
    </select>
  </fieldset>
</form>