Context:
I’ve been using an autocomplete package and it’s just not got the functionality that i’m needing.
The idea is to have a reusable component that loads in a list of item that has a checkbox input, you select the option(s) you need, then submit the form:
<div {{ stimulus_controller('autocomplete-select', {
// path to load list of items [in this case users]
url: path('_user_search')
}) }}>
// display the autocomplete results
<div data-autocomplete-select-target="autocompleteResult"></div>
</div>
_user_search end point loads in the list of users
{% for user in users %}
<div class="list-group-item">
<input class="form-check-input" type="checkbox" role="option" data-id="{{ user.id }}"/>
</div>
{% endfor %}
autocomplete-select_controller.js
export default class extends Controller {
static targets = ['textInput', 'autocompleteResult', 'selected', 'itemCheckbox', 'input']
static values = {
url: String,
option: String
}
connect () {
console.log('autocom select connected')
this.textInputTarget.addEventListener('keyup', (e) => {
axios.get(this.urlValue, {
params:{
q: this.textInputTarget.value
}
}).then((response) => {
this.autocompleteResultTarget.innerHTML = response.data
let options = document.querySelectorAll('[role="option"]')
options.forEach((option)=>{
option.addEventListener('click', (e) => {
console.log(option.getAttribute('data-id'))
})
})
})
})
}
}
Problem:
Whenever I select an option, and then search for another, of course the data is reloaded and the checked checkbox is lost.
Any suggestions of how I can refactor this to keep the checked checkboxes even on reload. I was looking a saving state in the documentation, but I’m unsure how to implement it in this case.
I’ll be creating a public package, once this is resolved.