我的登录页面使用 Django 的表单。 我想在页面加载时将焦点设置到第一个文本字段(用户名)。
我尝试按如下方式使用 Jquery,但没有得到结果。
forms.py:
from django import forms
class LoginForm(forms.Form):
userName = forms.EmailField(max_length=25)
password = forms.CharField( widget=forms.PasswordInput, label="password" )
登录.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>
最佳答案
正确的 Django 回答这个问题的方式如下(因为它不依赖于是否启用 js):
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'})
另外,郑重声明,我们避免对对象属性使用驼峰命名法。干杯!
关于javascript - 如何将焦点设置到 Django 表单元素的 CharField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8255346/