Reset MDBSelect


Topic: Reset MDBSelect

balcamo pro premium priority asked 2 years ago

I have a modal form with a clear button that I want to use to reset the input values and validation errors. The form has 1 select and 1 text input.

When the user clicks the clear button, the text input is clearing and resetting, but the select is not. I was able to get the validation errors to remove by using this jquery

I created two identical lists for the select options. The select data attribute is tied to codeSelect and on clear I set codeSelect to the default list.


Krzysztof Wilk staff answered 2 years ago

Hi!

For that purpose, you should use the type of reset button or just form.reset() method (i.e. $("#serviceRequestForm").reset()) to achieve that. You can also pass this clearForm function to an onReset callback in the MDBValidation component to update the select data or other form values :)


balcamo pro premium priority commented 2 years ago

The reset button does not work on the select element, only the input.


balcamo pro premium priority answered 2 years ago

I no longer need this resolved as I've removed this select feature from the project.


mlazaru staff answered 2 years ago

Use this code to reset Select options with external button:

import React, { useState } from "react";
import { MDBBtn, MDBContainer, MDBSelect } from "mdb-react-ui-kit";

const defaultSelectOptions = [
  { text: "One", value: 1, defaultSelected: true },
  { text: "Two", value: 2 },
  { text: "Three", value: 3 },
];

export default function App() {
  const [selectValue, setSelectValue] = useState(defaultSelectOptions);

  const resetForm = () => {
    setSelectValue([...defaultSelectOptions]);
  };

  return (
    <form>
      <MDBContainer className="my-5">
        <MDBSelect className={"my-3"} data={selectValue} value={3} />
        <MDBBtn type="button" onClick={resetForm}>
          Reset form
        </MDBBtn>
      </MDBContainer>
    </form>
  );
}

In this case, select component re-evaluates when data prop is changed. setSelectValue([...defaultSelectOptions]) creates a new array from defaultSelectOptions and it's recognized as a new value, even if the data in the array is exactly the same.

You can't use setSelectValue(defaultSelectOptions) because it doesn't change array-items or array itself, so select won't see the difference and will keep current state.


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue
  • User: Pro
  • Premium support: Yes
  • Technology: MDB React
  • MDB Version: MDB5 5.1.0
  • Device: Desktop
  • Browser: Chrome
  • OS: Windows
  • Provided sample code: No
  • Provided link: No