Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to set focus on first input element in a Volt form

Hi,

I am using Phlacon v3. I would like to set default focus to be on the first field of my Volt form. I have tried both autofocus and tabindex=1 in the volt view but nothing seems to make any difference. I am using Form. Tried adding these clauses to the form too but nothing seems to be working. It always focuses on a field with select list which is 6th field on the form.

Code below:

<div class="col-sm-3">
    {{ form.render("care_id", ["class" : formFieldClass, "id" : "fieldCareId", 'autofocus' : 'autofocus']) }}
</div>
OR
<div class="col-sm-3">
    {{ form.render("care_id", ["class" : formFieldClass, "id" : "fieldCareId",  'tabindex' : '1']) }}
</div>

Not sure what's going on.

Thanks, Amal



110.7k
Accepted
answer

autofocus should work. What does the resulting HTML look like?



14.7k
edited Mar '20

Sorry for the late reply @quasipickle. The HTML has autofocus. Here is the generated phtml file code.

<div class="row">
    <div class="form-group">
        <label for="fieldCareId" class="col-sm-1 control-label">Care ID</label>
        <div class="col-sm-3">
            <?= $form->render('care_id', ['class' => $formFieldClass, 'id' => 'fieldCareId', 'autofocus' => 'autofocus']) ?>
        </div>
...
...

What does the HTML look like once it gets to your browser?



14.7k
<div class="row">
    <div class="form-group">
        <label for="fieldCareId" class="col-sm-1 control-label">Care ID</label>
        <div class="col-sm-3">
            <input type="text" id="fieldCareId" name="care_id" class="form-control form-control-inline" maxlength="50" autofocus="autofocus" />
        </div>
 ...
 </div>

autofocus is a boolean attribute. It works just by existing - not by having a particular value. While what you have should work, try changing your code to 'autofocus':true. Admittedly, I'm kind of grasping at straws.

Have you tested this in Firefox and Chrome? I saw an old post where autofocus = "autofocus" didn't work in old Firefox.

Finally, is this field visible on page load? autofocus won't bring focus to a field that isn't visible on page load.



14.7k
edited Mar '20

Ok, its working, my mistake. It was not working earlier so I had put some javascript to focus on the first field. This was interefering and changing the focus. I had picked the offending JS from a stackoverflow post. Both autofocus = "autofocus" and autofocus = ""work.

Just FYI, the offending JS which should have worked but wasn't doing its job. It looks for first not readonly, enabled, not hidden field to focus on.

$("form:eq(1) *:input[type!=submit],select,textarea").filter(":not([readonly='readonly']):not([disabled='disabled']):not([type='hidden'])").first().focus();