wtreston
wtreston

Reputation: 1061

Get all input values into a list javascript

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']

Upvotes: 1

Views: 2116

Answers (1)

janos
janos

Reputation: 124656

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

Upvotes: 1

Related Questions