Choices icon indicating copy to clipboard operation
Choices copied to clipboard

Highlighting and selecting first item from store programatically

Open juniorgarcia opened this issue 5 years ago • 6 comments

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 avatar May 16 '19 12:05 juniorgarcia

@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 avatar Jul 10 '19 07:07 hoektoe

@hoektoe Still with this issue.

juniorgarcia avatar Jul 10 '19 13:07 juniorgarcia

Ok i'll have a look at the source and maybe can propose a PR to maintainer

hoektoe avatar Jul 16 '19 12:07 hoektoe

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 avatar Jun 23 '22 08:06 mattgreenfield

@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;
}

webinformat avatar May 12 '23 10:05 webinformat

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)
})

bupy7 avatar Jan 20 '24 18:01 bupy7