[英]In Django, how to make selecting a drop-down option automatically submit a form?
I'm trying to implement a form which pre-populates fields based on another field. 我正在尝试实现一种表单,该表单根据另一个字段预先填充字段。 As a starting point, I'd like to make the form 'auto-submit' when an option from a drop-down menu is selected.
首先,我希望在从下拉菜单中选择一个选项后,将表单设置为“自动提交”。 I've tried the following template:
我尝试了以下模板:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(".auto-submit").change(function() {
$(this).closest("form").submit();
});
</script>
<form action="" method="post">{% csrf_token %}
{% for field in form %}
{% if field.name == "checkin_type" %}
<div class="auto-submit">
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
</div>
{% else %}
<div>
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
</div>
{% endif %}
{% endfor %}
<input type="submit" value="Send message" />
</form>
where the view is based on Django's generic CreateView
: 该视图基于Django的通用
CreateView
:
from django.views import generic
from .models import CheckIn
class CheckInCreate(generic.CreateView):
model = CheckIn
fields = '__all__'
and the models are 和模型是
from django.db import models
from django.urls import reverse
class CheckInType(models.Model):
title = models.CharField(blank=True, max_length=255)
description = models.TextField(blank=True)
def __str__(self):
return self.title
class CheckIn(models.Model):
checkin_type = models.ForeignKey(CheckInType, null=True, on_delete=models.CASCADE)
title = models.CharField(blank=True, max_length=255)
description = models.TextField(blank=True)
notes = models.TextField(blank=True)
# Scheduling
requested_date = models.DateField(blank=True, null=True)
completed_date = models.DateField(blank=True, null=True)
def get_absolute_url(self):
return reverse('checkin-detail', kwargs={'pk': self.id})
def save(self, *args, **kwargs):
if self.checkin_type:
if not self.title:
self.title = self.checkin_type.title
if not self.description:
self.description = self.checkin_type.description
super().save(*args, **kwargs)
However, if I actually select a drop-down menu option in the browser, nothing happens. 但是,如果我实际上在浏览器中选择了一个下拉菜单选项,则什么也不会发生。 Can someone explain why this is not working?
有人可以解释为什么这行不通吗?
You're trying to attach the event handler before the drop down menu is loaded into the DOM. 您正在尝试在下拉菜单加载到DOM之前附加事件处理程序。 You can use document.ready to wait until it is loaded to attach the handler
您可以使用document.ready等待加载完成后附加处理程序
$(document).ready(function(){
$(".auto-submit").change(function() {
$(this).closest("form").submit();
//this.form.submit(); //less verbose
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.