简体   繁体   中英

How Set focus to CharField of a django form element

Am using Django's form for my login page. I want to set focus to the first textField (username) when the page loads. I tried using Jquery as follows, But doen't get the result.

forms.py:
from django import forms
class LoginForm(forms.Form):
    userName = forms.EmailField(max_length=25)     
    password = forms.CharField( widget=forms.PasswordInput, label="password" )

Login.html

% block headextra %}
    <script type="text/javascript">
        $(document).ready(function() {
             window.onload = function() {
             $("#id_username").focus();
             // alert('test') if I add this line its works
             //  setting focus to a textbox which added to template page direcltly using html tag the focus() method works well
            };  
        }); 
        </script>       
    {% endblock %}

{% block content %} 
<form method = "POST" action ="/login/">{% csrf_token %}
<table align ="center">
    {{ form.as_table }}
<tr><td></td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
</table>
</from>

The proper Django way of answering this question is as follows (as it doesn't depend on js being enabled):

from django import forms

class LoginForm(forms.Form):
    user_name = forms.EmailField(max_length=25)     
    password = forms.CharField( widget=forms.PasswordInput, label="password" )

    def __init__(self):
        self.fields['user_name'].widget.attrs.update({'autofocus': 'autofocus'
            'required': 'required', 'placeholder': 'User Name'})
        self.fields['password'].widget.attrs.update({
            'required': 'required', 'placeholder': 'Password'})

Also, for the record, we avoid the use of camelcase for object attributes. Cheers!

    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'autofocus': 'autofocus'}))

for text input:

    field = forms.CharField(
        widget=forms.TextInput(attrs={'autofocus': 'autofocus'}))

I just wanted to use the default Django login form, but add the autofocus attribute, so I derived a new form class from the default.

#myapp/forms.py
from django.contrib.auth.forms import AuthenticationForm

class LoginForm(AuthenticationForm):
    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.update({'autofocus': ''})

Then I specified the new form class in urls.py :

from myapp.forms import LoginForm

urlpatterns = patterns(
    '',
    url(r'^login/$', 'django.contrib.auth.views.login',
        {"template_name": "myapp/login.html",
         "authentication_form": LoginForm,
         "current_app": "myapp"}, name='login'),
    #...
    )

In html, all you need is autofocus without arguments.

In the Django form, add autofocus as key with empty value:

search = forms.CharField(
                label='Search for:',
                max_length=50,
                required=False,
                widget=forms.TextInput(attrs={'autofocus': ''}))

$("#id_username")应该是$("#id_userName")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM