Choices icon indicating copy to clipboard operation
Choices copied to clipboard

Resetting the form clears the list of choices

Open mscart opened this issue 2 years ago • 7 comments

I have a form with some filters that make an ajax request to display a table. When I want to reset the filters ( $("#filter-form").trigger("reset");) all the select elements created with choices.js are empty and I have nothing left to select. I have to refresh the page to repopulate the select forms. any ideea ?

mscart avatar Sep 02 '22 06:09 mscart

I'm experiencing the same issue... how can we handle this scenario?

masiorama avatar Sep 09 '22 09:09 masiorama

Having the same issue. Is there a fix for this?

kumardeepakme avatar Oct 05 '22 15:10 kumardeepakme

The same issue when I clear form inputs. Still no fix?

Sogl avatar Dec 18 '22 11:12 Sogl

Ran into the same problem.

I got an idea from issue #1023.

My band-aid is to add an addEventListener() for the form reset. Then, use Choices setChoices() method to re-populate the select element from the variable pointing to the select element.

It still allows the form normal reset process to work.

document.addEventListener('DOMContentLoaded', function () {
	const choicejsOptions = {
		allowHTML: false,
		removeItemButton: true,
		searchEnabled: true,
		searchChoices: true,
		searchFields: ['label', 'value'],
		placeholder: true,
	};

	const selectList = new Choices('.js-choice__SelectListID', choicejsOptions);

	document.querySelector('form').addEventListener('reset', function () {
		console.log('reset');
		// console.log(selectList);

		selectList.setChoices(function () {
			return selectList.config.choices.map(({ value, label }) => ({
				value,
				label,
				selected: false,
			}));

		});
	});
});

jamesperrin avatar Feb 22 '23 22:02 jamesperrin

Even the documentation shows the bug. It removes all of the options when I click the reset button

ceciiiron avatar May 26 '23 00:05 ceciiiron

A work-around (snippet from a Stimulus controller):

const choices = new Choices(this.element, {
  allowHTML: false,
  removeItemButton: this.element.multiple,
});

const form = this.element.closest("form");
if (!form) return;

form.addEventListener("reset", () => {
  choices.destroy();
  choices.init();
});

MatheusRich avatar Nov 14 '23 15:11 MatheusRich