简体   繁体   English

如何获得附加元素的值

[英]How to get the value of appended elements

I have a form which involves entering a question. 我有一个涉及输入问题的表格。 The form initially has 2 input slots for choices to that question, but clicking a button will append another input to add another choice. 表单最初有2个input槽供您选择该问题,但是单击按钮将附加另一个input以添加另一个选择。 Problem is I can't get the value to these appended elements. 问题是我无法获取这些附加元素的值。 Any idea how else I can do it? 知道我还能怎么做吗? Here's my code: 这是我的代码:

models 楷模

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

views 意见

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})

template 模板

<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 (adds another input for the choice field) 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' />");
});

Since you will have multiple elements naming class 'choice', you can simply iterate over them to extract the value while submission. 由于您将有多个元素命名为“ choice”类,因此您可以简单地对其进行迭代以在提交时提取值。

$.each($('.choice'), function() {
    var data_value =  $(this).val();
    alert(data_value);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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