tomter2014
tomter2014

Reputation: 313

How do I autofocus a cursor in this django form?

In the following template, how do I force the cursor to autofocus into the form.username field when the browser loads?


{% block content %}

    <form method="post" action="">
    {% csrf_token %}
    <table>
    <tr>
        <td>{{ form.username.label_tag }}</td>
        <td>{{ form.username }}</td>
    </tr>
    <tr>
        <td>{{ form.password.label_tag }}</td>
        <td>{{ form.password }}</td>
    </tr>
    </table>

    <input type="submit" value="login" style="position: relative; left: 5em;" />
    <input type="hidden" name="next" value="{{ next }}" />
    </form>

    <p><a href="/register/" class="textf" style="position: relative; left: 8em;">Register</a></p>
{% endblock %}

Upvotes: 2

Views: 3852

Answers (3)

Laurent
Laurent

Reputation: 1806

In your forms.py define the field with the autofocus attribute:

username = forms.CharField(
    label=_('Username'),
    strip=True,
    widget=forms.TextInput(attrs={'placeholder': _('Username'), 'class': 'form-control', 'autofocus': True})
)

https://docs.djangoproject.com/en/2.1/ref/forms/widgets/#django.forms.Widget.attrs

Upvotes: 3

seddonym
seddonym

Reputation: 17249

You could just do it with javascript (in this example, Jquery). Make sure there is a block called extra_scripts in your base.html (just above the closing </body> tag), and then add the javascript as follows:

{% block content %}

    <form method="post" action="">
    {% csrf_token %}
    <table>
        <tr>
            <td>{{ form.username.label_tag }}</td>
            <td>{{ form.username }}</td>
       </tr>
    ...
{% endblock %}

{% block extra_scripts %}
    <script type="text/javascript">
        $(function () {
            // When the page has finished loading,
            // autofocus on the username field
            $('input#id_username').focus();
        });
    </script>
{% endblock %}

If you're not already using Jquery you will need to include a link to it in the page too (something like <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>).

Upvotes: 0

sinitsynsv
sinitsynsv

Reputation: 893

You can use django-widget-tweaks

<td>{{ form.username|attr:"autofocus" }}</td>

Also it can add attributes and classes, render fields with custom template and more

Upvotes: 1

Related Questions