Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Highlighting and selecting first item from store programatically #586

Open
juniorgarcia opened this issue May 16, 2019 · 6 comments
Open
Labels

Comments

@juniorgarcia
Copy link

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?

@hoektoe
Copy link

hoektoe commented Jul 10, 2019

@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.

@juniorgarcia
Copy link
Author

@hoektoe Still with this issue.

@hoektoe
Copy link

hoektoe commented Jul 16, 2019

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

@mattgreenfield
Copy link

It's not meant to be called but there is this

_highlightChoice(el: HTMLElement | null = null): void {

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.

@webinformat
Copy link

webinformat commented May 12, 2023

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

@bupy7
Copy link

bupy7 commented Jan 20, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

6 participants