Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
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. 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)

$(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' />");
});
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Since you will have multiple elements naming class 'choice', you can simply iterate over them to extract the value while submission.

$.each($('.choice'), function() {
    var data_value =  $(this).val();
    alert(data_value);
});
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda