如何将焦点设置为Django表单元素的CharField [英] How Set focus to CharField of a django form element

查看:311
本文介绍了如何将焦点设置为Django表单元素的CharField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Django的表单用于我的登录页面. I want to set focus to the first textField (username) when the page loads.我尝试如下使用Jquery,但没有得到结果.

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

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>

推荐答案

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

这篇关于如何将焦点设置为Django表单元素的CharField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆