Igor  Tischenko
Igor Tischenko

Reputation: 640

django: list transfer to template and to JS

In Views.py i create a list variable -

mortgages_counter.append(MonthlyPaymentAmount)

it is transferred to .html template as:

<input id ='mortgages_counter' name='mortgages_counter' type='hidden' value='{{mortgages_counter}}'>

in JQuery (separate file i have to check if each element of this list is used). value is transferred to .js file as:

var mortgages_counter = $('#mortgages_counter').val();

but according to console it was transferred as a string to Jquery - like ['1234','125'] and its length is 1 because of some reason, also check like access to index [0] gives - ' and [1] - 1 etc. how to operate with this list as with LIST and NOT a string?

Upvotes: 0

Views: 146

Answers (2)

MD. Khairul Basar
MD. Khairul Basar

Reputation: 5110

Though @JulienGregoire already answered, I'm mentioning another approach. You can run a loop through the mortgages_counter and add each item to an input tag. Then in Jquery use .each() to go through each object and check.

In your template do something like this.

{% for mortgages in mortgages_counter %}
    <input id='mortgages_counter' name='mortgages_counter' type='hidden' value='{{ mortgages }}'>
{% endfor %}

And in your Jquery use .each() like this.

$("#mortgages_counter").each(function () {
    var mortgage = $(this).val();
    /* do rest of the things and/or comparisons */
});

Upvotes: 1

Julien Gr&#233;goire
Julien Gr&#233;goire

Reputation: 17114

You should put the value as a string, which you can do by using join filter. Use a separator you know won't be used in the values of the list. Like this for example:

<input id ='mortgages_counter' name='mortgages_counter' type='hidden' value='{{mortgages_counter||join:"|" }}'>

See: https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#join

Then you split in javascript using the same separator. It converts the string to an array:

var mortgages_counter = $('#mortgages_counter').val().split('|');

https://www.w3schools.com/jsref/jsref_split.asp

Upvotes: 0

Related Questions