Choices
Choices copied to clipboard
Highlighting and selecting first item from store programatically
Using setChoiceByValue
selects the item, but does not highlight it. How can I highlight some item and also select the first item from the store?
@juniorgarcia did you manage to get a solution to this problem. I am trying to use setChoicesByValue for determined value, but when you open the dropdown ( without hover over any choices ) the "selected" choice is not highlighted.
@hoektoe Still with this issue.
Ok i'll have a look at the source and maybe can propose a PR to maintainer
It's not meant to be called but there is this https://github.com/Choices-js/Choices/blob/06d16cd857f96d6a1daefe5bd8ab56c48b925c76/src/scripts/choices.ts#L1883
You'll have to first find the element you want to highlight, this this
const selectedVal = this.value;
const el = document.querySelector(`.choices__list--dropdown .choices__item[data-value="${selectedVal}"]`)
choices._highlightChoice(el);
Personally, I'd agree that this is a bug.
@mattgreenfield here is the version for setting the higlighted element when you have multiple select choices
const selectedVal = this.value;
const el = getElementById('your-select-element-id').parentElement.nextSibling.querySelector(`.choices__list--dropdown .choices__item[data-value="${selectedVal}"]`)
choices._highlightChoice(el);
The higlighted element changes when you hover so you have to set in CSS the background for the selected item:
.choices__list--dropdown .choices__item--selectable.is-selected {
background-color: #f2f2f2;
}
.choices__list--dropdown .choices__item--selectable.is-selected:after {
opacity: 0.5;
}
As another option:
selectEl.addEventListener('showDropdown', () => {
const selected = choicesInstance.getValue()
if (typeof selected === 'string' || Array.isArray(selected)) {
return
}
const selectedEl = choicesInstance.dropdown.element.querySelector<HTMLElement>(`[data-value="${selected.value}"]`)
if (selectedEl === null) {
return
}
choicesInstance._highlightChoice(selectedEl)
})