简体   繁体   中英

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 :

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. You can use document.ready to wait until it is loaded to attach the handler

$(document).ready(function(){
    $(".auto-submit").change(function() {
        $(this).closest("form").submit();
        //this.form.submit(); //less verbose
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM