0
我有一個涉及輸入問題的表單。該表格最初有2個input
插槽用於選擇該問題,但單擊一個按鈕將附加另一個input
以添加另一個選項。問題是我無法獲得這些附加元素的價值。任何想法我能做到嗎?這裏是我的代碼:如何獲取附加元素的值
車型
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
意見
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})
模板
<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(又增加了輸入選擇字段)
$(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' />");
});