dequelabs / combobo

Accessible combobox
https://dequelabs.github.io/combobo/demo/
MIT License
49 stars 13 forks source link

[Feature Request] Option for selected items #23

Open MPSinclair opened 6 years ago

MPSinclair commented 6 years ago

Currently when building a combo box, having any elements with the selected attribute set does not populate the combo box's selected elements, as well it does not trigger the selectionValue function.

This would be especially useful when re-populating a series of combo boxes based on the previously submitted content.

Sorry if this is something that already exists and I simply missed.

schne324 commented 6 years ago

Thanks @MPSinclair ! Yea this seems like a bug, I totally agree that combobo should pick up on any aria-selected options upon instantiation.

Until this bug is fixed there is a workaround (not the cleanest solution but still accomplishes the goal of initial selections)

// you'd do this for EACH option you want to be initially selected (assuming you know it's index)
combobo.goTo(ID_OF_OPTION_TO_BE_SELECTED).select();

// alternatively you could
combobo.cachedOpts.forEach((opt, i) => {
  if (opt.getAttribute('aria-selected') !== 'true') {
    return;
  }

  combobo.goTo(i).select();
});
MPSinclair commented 6 years ago

Thank you so much for that! I did have to make one minor tweak. I noticed that when I used the alternate method, the first call to select() would result in the rest of the options having their 'aria-selected' attribute being set to false.

Instead I built a list of the option IDs in the first forEach loop, then iterated over those with the goTo(id).select() function.

var presets = [];
combobo.cachedOpts.forEach((opt, i) => {
  if (opt.getAttribute('aria-selected') !== 'true') {
    return;
  }

  presets.push(i);
});

presets.forEach((key, idx) => {
  combobo.goTo(key).select();
});

Thanks again!