How do I save a jinja variable to a list in javascript?

Viewed 257

I am using Django to create a web app for running a ranked election system. I have created a template for saving the ranking of the ballot paper. Here is what I have so far in the template:

<div id='main'>
    {% for candidate in candidates %}
    <div class='box'>
        <h3>{{candidate.UserID}}</h3>
        <input type=text>
    </div>
    {% endfor %}
</div>
<button id='send' type="submit">Submit</button>

<script type="text/javascript">

$(document).ready(function() {

var button = $("#send");

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

At the minute, the list just puts the values that the user inputs to the box into the list in order. What I want to do now is create a separate list that stores the name or the id of the candidate, an entry on a table which I queried and passed to the template using Django and rendered above using Jinja.

This is so that I can relate the rank to the candidate that has been ranked. I am doing this using JavaScript so that I can then process the two lists and return to Django (possibly with Ajax) a new list with the candidateIDs in the order the candidates were ranked.

I will have a dynamic number of candidates who need to be rendered and recorded. I may also, in future, randomize the order of the candidates, hence why I need to create a new list to relate them. Can the jinja variable be added directly to the JavaScript list?

I have very little experience using JavaScript and HTML; what JavaScript I have here was done with a lot of help from a friend. Therefore, I am asking how to implement the code as described above.

Thank you in advance for your help.

0 Answers
Related