I am new to jQuery.
I tried getting/summing some items from my django views in jQuery. This is what I have:
$(document).ready(function()
{
var sch = $('#sch-books');
var gov = $('#gov-books');
var total = sch.val() + gov.val();
$('#total').text("Total : " + total);
});
My template has this:
<div id="sch-books" class="h6 mb-1">School copies - <b>{{ s_books.count }}</b></div>
<div id="gov-books"class="h6 mb-1">Govt copies - <b>{{ g_books.count }}</b></div>
<div id="total"></div>
It displays Total :
May someone help me get it right..
you can try to use django-mathfilter for this purpose.because javascript can be disabled by the user and django-mathfilter is so powerfull.
$ pip install django-mathfilters
Then add mathfilters to your INSTALLED_APPS.
then in you template you can just do something like this.
{% load mathfilters %}
........
{% with s_books.count as s_book and g_books.count as g_book %}
<div id="sch-books" class="h6 mb-1">School copies - <b>{{ s_book }}</b></div>
<div id="gov-books"class="h6 mb-1">Govt copies - <b>{{ g_book }}</b></div>
<div id="total">{{ s_book|add:g_book }}</div>
{% endwith %}
for more information read this https://pypi.org/project/django-mathfilters/
Instead of involving the js script, I will recommend creating total_value on the Django side and moving it to the template.
<div class="h6 mb-1" data-count="{{ s_books.count }}">School copies - <b>{{ s_books.count }}</b></div>
<div class="h6 mb-1" data-count="{{ g_books.count }}">Govt copies - <b>{{ g_books.count }}</b></div>
<div>{total_count}</div>
I am not sure which way you follow to render the template, but should look at this one
# views.py
from django.shortcuts import render
def render_users(request):
g_books = {}
s_books = {}
context = {
"g_books": g_books,
"s_books": s_books,
"total_count": g_books.count + s_books.count
}
return render(request, 'books.html', context)
val() returns value attribute like in <input type="text" value=something/> and html() returns the content (innerHTML) of selected element.
So modify your codes like this and you are good to go.
(I am assuming that django returns a numeric value in {{ s_books.count }} and {{ g_books.count }}).
$(document).ready(function()
{
var sch = $('#sch-books b').html(); // added b element and calling html()
var gov = $('#gov-books b').html(); // added b element and calling html()
var total = parseInt(sch) + parseInt(gov); // converted the string into number using parseInt()
$('#total').text("Total : " + total); // worked
});