【发布时间】:2016-05-22 11:12:33
【问题描述】:
我正在从LocForm 记录city 字段的值,但在输入一个值并点击提交按钮后,$('#post-text').val() 将返回undefined 作为其值。控制台输出为:
form submitted!
create post is workin
undefined
以下是代码的主要部分:
views.py:
def home(request):
form = LocForm()
context = {
"form" : LocForm
}
return render(request, 'home.html', context)
forms.py: (表单)
class LocForm(ModelForm):
class Meta:
model = Location
fields = ['city']
labels = {
'city': ('Where do you want to live'),
}
widgets = {
'city': forms.TextInput(attrs = {
'id': 'post-text',
'required': True
}),
}
main.js:(主要的 javascript 文件)
$('#post-form').on('submit', function(event) {
event.preventDefault();
console.log("form submitted!")
create_post();
});
function create_post() { //AJAX call
console.log("create post is workin");
console.log($('#post-text').val());
});
};
来自模板的表单 html 代码:
<form id="post-form" action="/create_post/" method="post" style="text-align: center">
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-lg btn-primary" type="submit" value="submit">
</form>
【问题讨论】:
-
首先,您不需要
document.ready函数内的document.ready处理程序,因此您可以将其删除。其次,您的 HTML 代码中的哪个位置是#post_text元素? -
是
$(document).ready导致了您的问题。 @rory-mccrossan OP 正在为表单类中的字段设置自定义 IDpost-text。 -
@RoryMcCrossan 这是我关于堆栈溢出的第一个问题,所以感谢您的编辑:) 我已经删除了 document.ready 但仍然没有效果。
#post_text是LocForm内的元素的 ID,我已在<form>标记内导入了{{ form|crispy }}。我还添加了我的 views.py 以提供更多详细信息。