Autofocus on corresponding field after changing combobox value

Hi from this page, I’m trying to autofocus on nearby field after I change the value of one of these comboboxes: Autore, Titolo, Soggetto, Classificazione, Libera. I used this userscript, each field gets clicked for a fraction of second, but not autofocused:

// Get all the select elements
var selectElements = document.querySelectorAll('select[name="canale"]');

// Add change event listener to each select element
selectElements.forEach(function(selectElement) {
  selectElement.addEventListener('change', function() {
    // Get the parent li element
    var liElement = this.closest('li');

    // Get the input field within the same li element
    var inputField = liElement.querySelector('input[type="text"]');

    // Set focus on the input field
    inputField.focus();
  });
});

Thank you!

Hi @lawrencedaniello, it appears that the sebinayou library you’re using is replacing those entire list item elements on mouse up, so the text input elements (along with their siblings) are getting removed right after receiving focus… which BTW also causes the change event listeners only getting called once per list item. This library looks quite heavy and I can’t find a documentation, do you have a particular invocation in your code though that might be responsible for this?

1 Like

Mhm, I haven’t got it… I don’t know if this page could help, as it has a similar structure…

Well no this page just features the same library and does the same thing… :-/ Just digging a bit deeper though, there’s an AJAX request getting sent on on each mouse up event, and the list items are then getting replaced with new markup from the response body… any idea where this is coming from?

The only (rather awkward) workaround I’d come up with at this point would be to instantiate a mutation observer, which would observe the criteria list and focus the text input fields of those newly added list items:

const observer = new MutationObserver(mutations => {
  mutations.forEach(record => {
    record.addedNodes.forEach(node => {
      // The list item got replaced with new markup, now
      // we can focus the text input element... oh well
      node.querySelector('input[type="text"]').focus()
    })
  })
})

const criteria = document.querySelector('.criteria')

observer.observe(criteria, { childList: true })
2 Likes

Wao, thanks very much m3g4p0p! Is it possible to apply a similar script here, so autofocusing when combobox value changes? Thank again!

1 Like

Glad I could help. :-) And sure, you can observe any element for child list modifications this way. For more complex elements you might need to set the subtree option, so that not only direct children but any descendants are getting watched… check out the above MDN link for details!

Mhm, I’ll try, thanks!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.