Ich habe ein Formular, das die Eingabe einer Frage beinhaltet. Das Formular hat anfänglich 2 input
Steckplätze für die Auswahl dieser Frage, aber wenn Sie auf eine Schaltfläche klicken, wird eine weitere input
hinzugefügt, um eine weitere Auswahl hinzuzufügen. Problem ist, dass ich den Wert für diese angehängten Elemente nicht erhalten kann. Irgendeine Idee, wie sonst kann ich es tun? Hier ist mein Code:Wie bekomme ich den Wert von angehängten Elementen
Modelle
class Question(models.Model):
has_answered = models.ManyToManyField(User, through="Vote")
question_text = models.CharField(max_length=80)
date = models.DateTimeField(auto_now=True)
total_votes = models.IntegerField(default=0)
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=100)
votes = models.IntegerField(default=0)
percent = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
Ansichten
def questions(request):
question_form = QuestionForm(request.POST or None)
choice_form = ChoiceForm(request.POST or None)
if request.user.is_authenticated():
if question_form.is_valid():
question = question_form.save(commit=False)
question.save()
choices = request.POST.getlist('choice_text')
for choice in choices:
Choice.objects.create(choice_text=choice, question=question)
else:
print(question_form.errors)
return render(request, 'questions.html', {'question_form': question_form, 'choice_form': choice_form})
Vorlage
<form method="post" action="">{% csrf_token %}
{{ question_form.question_text|placeholder:"Question" }}
<br><br>
<!--{{ choice_form.choice_text|placeholder:"Choice" }}-->
<input class="choice" name="choice_text" placeholder="Choice" type="text" />
<input class="choice" name="choice_text" placeholder="Choice" type="text" />
<img src="{% static 'images/plus.png' %}" class="add_choice" />
<button class="submit" type="submit">Submit question</button>
</form>
js (fügt einen weiteren Eingang für das Auswahlfeld)
$(document).on('click', '.add_choice', function(){
$(this).after('<input type="text" class="choice" placeholder="Choice" name="choice_text" /><img src="/static/images/plus.png"' + " class='add_choice' />");
});