0
votes

Hello i need to focus first field of ErrorBag, I am using Livewire component form and because Livewire send XHR request every input change to update the DOM it will be focused every time on XHR response without submitting the form and it's not what I need, I am using also Alpine Js in the same project and I want focus it with Javascript but I don't know if it is possible to watch a property changes.

function app(){

return {

    errorBag: {!! json_encode(array_keys($errors->getMessages())) !!},
    

    focusField()
    {
     if(this.errorBag.length > 0)
      {
        fieldError = Array.from(document.getElementsByName(errorBag[0]));
        fieldError[0].focus({preventScroll:false});
      }
    }
}

}

In example i want initialize the Alpine component with x-data="app()" and then i want trigger focusField() function if the errorBag property changes to focus only once the field invalid for every form submit. Thanks for your help

1
Your code has syntax errors, are you sure everything has been copied correctly?Zer0
I've updated the code, now you will not receive syntax errors.Nicola

1 Answers

1
votes

Solved myself

          <div
            x-data="
            { 
              'errors': {{ json_encode(array_keys($errors->getMessages())) }},
              focusField(input){
                  fieldError = Array.from(document.getElementsByName(input));
                  if(fieldError.length > 0){
                    fieldError[0].focus({preventScroll:false});
                  }
              },
            }
            "
            x-init="() => { $watch('errors', value => focusField(value[0])) }"
        >
        </div>

Properties in function app() are not updated,but in x-data object it works perfect.