Search code examples
laravellaravel-5laravel-form

Laravel: How do I autofocus an input field when there is/isn't an error in the var $error?


If there is an error in a particular input, I want to highlight it and focus it, and it works as expected.

However, if there are no errors (default case), the first input should focus, which it doesn't. How do I add these two options to the array? Take a look at the first form group.

<div class="form-group {{ $errors->has('name') ? ' has-error' : '' }}">
    {{ Form::text('name', null, [
        (!$errors) ? 'autofocus' : '',        // if no errors, autofocus because default
        ($errors->has('name')) ? 'autofocus' : ''   // if error in name, autofocus
    ]) }}
</div>

<div class="form-group {{ $errors->has('email') ? ' has-error' : '' }}">
    {{ Form::email('email', null, [
        ($errors->has('email')) ? 'autofocus' : ''   // if error in email, autofocus
    ]) }}
</div>

<div class="form-group {{ $errors->has('password') ? ' has-error' : '' }}">
    {{ Form::password('password', [
        ($errors->has('password')) ? 'autofocus' : ''   // if error in password, autofocus
    ]) }}
    </div>
</div>

Solution

  • This should work:

    ....
    'autofocus' => $errors->has('password') ? 'autofocus' : null,
    ....