How Set focus to CharField of a django form element
$("#id_username")
should be $("#id_userName")
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': ''}))
password = forms.CharField(
widget=forms.PasswordInput(attrs={'autofocus': 'autofocus'}))
for text input:
field = forms.CharField(
widget=forms.TextInput(attrs={'autofocus': 'autofocus'}))
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!