josefarias / hotwire_combobox

An accessible autocomplete for Ruby on Rails.
https://hotwirecombobox.com
MIT License
436 stars 26 forks source link

Programmatically clear the input #183

Closed searls closed 2 weeks ago

searls commented 1 month ago

I need to be able to clear out the selection of a combobox with JavaScript. Right now I'm blanking out the value of the input, but this doesn't reset the UI's state (an "X" still appears, the list is pre-populated with the previously-selected item, etc.).

Is there a way to do this?

ryanckulp commented 1 month ago

you should be able to invoke this same function as the Stimulus controller (upon clicking the x graphic in far right of input box).

image

searls commented 1 month ago

Yes, but that method will also focus / open the list. What I ultimately did was write a monkeypatch:

// app/javascript/ext/hotwire_combobox_ext.js
import HwComboboxController from 'controllers/hw_combobox_controller'

HwComboboxController.prototype.clearOnTomfoolery = function () {
  if (this._isQueried) {
    this._clearQuery()
  }
  this._actingCombobox.blur()
}

And then dispatched hw-combobox#clearOnTomfoolery on the element

josefarias commented 1 month ago

I had a brief chat about this with @brunoprietog and I think what we ultimately want is to decouple focusing and interacting with the combobox.

I do think we should support clearing programmatically without focusing. Whether the larger scheme decoupling is part of that work remains to be seen. I'll need to take a closer look.

I'm out of the country this weekend so I don't think I'll have time just yet. But hopefully soon! I've been thinking about this for a while, it's come up before.

josefarias commented 2 weeks ago

Went with an outlets approach. Managed to sidestep the focus coupling issue. But I'll keep it in mind.

Please do let me know if this doesn't work for you!