Reputation: 3725
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>
Upvotes: 12
Views: 14436
Reputation: 97
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': ''}))
Upvotes: 6
Reputation: 1866
password = forms.CharField(
widget=forms.PasswordInput(attrs={'autofocus': 'autofocus'}))
for text input:
field = forms.CharField(
widget=forms.TextInput(attrs={'autofocus': 'autofocus'}))
Upvotes: 12
Reputation: 56230
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'),
#...
)
Upvotes: 2
Reputation: 4338
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!
Upvotes: 28
Reputation: 118508
$("#id_username")
should be $("#id_userName")
Upvotes: 2