Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
Trigger onChange function even if an option is already chosen in react

I'm looking how to trigger onChange function when an option is already selected and clicked by the user to deselect it, it's like multiselect. you can select an option and deselect it by clicking on it a second time. this is what i've already tried. everything is working when there is more than 1 option selected, but not when there is only one option selected.

const handleChangeGroup = (selectedItems) => {
    const groups = [];
    for (let i = 0; i < selectedItems.length; i++) {
      if (groupArray.includes(selectedItems[i].value)) {
        if (groupArray.length === 0) {
          setGroupArray([]);
        } else {
          var newArray = groupArray.filter(
            (value) => value != selectedItems[i].value
          );
          setGroupArray(newArray);
        }
      } else {
        groups.push(selectedItems[i].value);
        setGroupArray(groupArray.concat(groups));
      }
    }
  };


<select
            multiple={true}
            value={groupArray}
            onChange={(event) =>
              handleChangeGroup(event.target.selectedOptions)
            }>
            {data[selectType] !== undefined
              ? Object.keys(data[selectType]).map((group, index) => (
                  <option value={group} key={group}>
                    {group}
                  </option>
                ))
              : null}
          </select>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Executable example:

const Sample = () => {
    const data = ['a', 'b', 'c'];
    const [groupArray, setGroupArray] = React.useState([]);

    const handleChangeGroup = (selectedItem) => {
        if (groupArray.includes(selectedItem)) {
            const tempArray = groupArray.filter(item => item !== selectedItem);
            setGroupArray([...tempArray]);
        } else {
            setGroupArray([...groupArray, selectedItem]);
        }
    };

    return (
        <select
            multiple
            value={groupArray}
            onClick={e => handleChangeGroup(e.target.value)}
        >
            {data.map((group, index) => (
                <option value={group} key={group}>
                    {group}
                </option>
            ))}
        </select>
    );
};

ReactDOM.render(<Sample />, document.querySelector("#app"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="app"></div>

You might want to consider using checkboxes for a more intuitive UI and more concise code.

If you don't want to use checkboxes, you can use this code:

const handleChangeGroup = (selectedItem) => {
    if (groupArray.includes(selectedItem)) {
        const tempArray = groupArray.filter(item => item !== selectedItem);
        setGroupArray([...tempArray]);
    } else {
        setGroupArray([...groupArray, selectedItem]);
    }
};

return (
    <select
        multiple
        value={groupArray}
        onClick={e => handleChangeGroup(e.target.value)}
    >
        {data[selectType] !== undefined
            ? Object.keys(data[selectType]).map((group, index) => (
                <option value={group} key={group}>
                    {group}
                </option>
            ))
            : null}
    </select>
);

The reason onChange won't work is because the default behavior of select is to make the user choose at least one option. Clicking on the last selected option will not deselect anything. So onChange won't fire when you have only one selected item left. You can override this replacing onChange with onClick.

For a simpler example/test, you can try using select without the multiple attribute. Clicking on the currently selected option won't fire any deselect events either.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!