1

When the response page renders, it renders various input fields. I am trying to get this into a list which, using ajax will be sent back to the django view. here is the html and javascript i am trying to use to achieve this.

<div id ='answers'>
{% for q in questions %}
{{q.question.numeric}}
{% if q.question.numeric%}
<div class = 'numeric_answer'>
    {{ q.question.question_text }}<br>
    <select name="Score">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>        
    </select>

</div>
{% else %}
<div class = 'text_answer'>
    {{ q.question.question_text }}<br>
    <input type="text" class="question_text"/><br>
</div>

{% endif %}


{% endfor %}
</div>

<button id="send">Submit</button>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script type="text/javascript">


$(document).ready(function() {

var button = $("#send");

$(button).click(function() {
    var vals = [];
    $("#answers :input").each(function(index) {
        vals.push(this.val);
    });
  vals = JSON.stringify(vals);
  console.log(vals);
});  
});
</script>

Currently, no matter what is entered, I get a list which just contains 'nulls' eg [null, null, null] when I want a list like ['hey', 'asdasd', 5, 'ásdas']

3
  • What is $("#answers :input") supposed to select? Commented Nov 19, 2017 at 8:02
  • Also it should be vals.push($(this).val()); and not vals.push(this.val);. Commented Nov 19, 2017 at 8:04
  • this is an native element, not a jQuery object. Either use this.value or $(this).val() Commented Nov 19, 2017 at 8:04

1 Answer 1

1

The problem is here:

$("#answers :input").each(function(index) {
    vals.push(this.val);
});

You need to pass the iterated element in the loop as the second parameter of the function, and then use its value property:

$("#answers :input").each(function(index, item) {
    vals.push(item.value);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.