Skip to content Skip to sidebar Skip to footer

How To Check If Any Form Element Inside A Fieldset Has Focus

I want to partially validate a form by validating all elements inside a fieldset. As a trigger for that validation, I'm listening to focusout events which bubble up to each fieldse

Solution 1:

Don't you just need to wait for the focus on the new element to happen? Like this:

const fieldsets = [...document.querySelectorAll('fieldset')]

for (const fieldset of fieldsets) {
  fieldset.addEventListener('focusout', (e) => {
    let ct = e.currentTarget;
    setTimeout(() => {
      let focussedElements = ct.querySelectorAll(':focus');
      if (focussedElements.length === 0) {
        console.log(`no element inside fieldset #${ct.id} has focus`)
      } elseif (focussedElements.length > 0) {
        console.log(`element ${focussedElements[0]} inside fieldset #${ct.id} has focus`)
      }
    }, 10)
  })
}
<fieldsetid="fs1"><legend>Fieldset 1</legend><inputtype="text"><inputtype="text"></fieldset><fieldsetid="fs2"><legend>Fieldset 2</legend><inputtype="text"><select><option>1</option><option>2</option></select></fieldset>

Post a Comment for "How To Check If Any Form Element Inside A Fieldset Has Focus"