I'm having this issue when sending a json response from my django app to a table using javascript/jquery.
I've seen other threads that say this is error is due to jquery not being used, and that we should add the link to jquery such as the following within the tags but i don't have head tags.
Query link:
<script src="http://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js></script>
<script src="http://cdn.datatables.net/1.10.24/js/dataTables.bootstrap4.min.js></script>
my welcome.html file with javascript and table html at the end:
{% extends 'base.html' %}
{% load static%}
{% comment %} <script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script> {% endcomment %}
{% comment %} <script src="http://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.js"></script> {% endcomment %}
{% block content %}
<!-- Upload File Section-->
<section class="page-section mt-5" id="import-form">
<div class="container">
<!-- Upload Section Heading-->
<h2
class="page-section-heading text-center text-uppercase text-secondary mb-0"
>
Upload Data
</h2>
<!-- Icon Divider-->
<div class="divider-custom">
<div class="divider-custom-line"></div>
<div class="divider-custom-icon"><i class="fas fa-star"></i></div>
<div class="divider-custom-line"></div>
</div>
<!-- Upload Data Section Form-->
<div class="row justify-content-center">
<div class="col-lg-8 col-xl-7">
<form id="upload-file" name="upload-file",
enctype="multipart/form-data" method="POST" action="{% url 'supplychain:airpollution' %}">
{% csrf_token %}
<!-- Year input-->
<div class="form-floating mb-3">
<input
class="form-control"
id="year"
name="year"
type="number"
placeholder="year"
data-sb-validations="required"
/>
<label>Year</label>
<div class="invalid-feedback" data-sb-feedback="name:required">
A name is required.
</div>
</div>
<!-- Data input-->
<div class="form-floating mb-3">
<input
class="form-control"
id="file"
name="file"
type="file"
data-sb-validations="required"
/>
<label>File</label>
<div class="invalid-feedback" data-sb-feedback="email:required">
An email is required.
</div>
<div class="invalid-feedback" data-sb-feedback="email:email">
Email is not valid.
</div>
</div>
<!-- Submit success message-->
<div id="success">{{ message_success }}</div>
<div class="form-group">
<button class="btn btn-primary btn-xl" id="upload" type="submit">Upload</button>
</div>
</form>
</div>
</div>
</div>
</section>
<!-- Table Section-->
<section class="page-section mt-5" id="data-table">
<div class="container">
<!-- Heading-->
<h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Data Table</h2>
<!-- Icon Divider-->
<div class="divider-custom">
<div class="divider-custom-line"></div>
<div class="divider-custom-icon"><i class="fas fa-star"></i></div>
<div class="divider-custom-line"></div>
</div>
<!-- Table-->
<div class="row">
<div class="col-lg-8 mx-auto">
<table id="our-table" class="table">
<thead>
<tr>
<th scope="col">Pollutant</th>
<th scope="col">Country</th>
<th scope="col">Avg</th>
<th scope="col">Min</th>
<th scope="col">Max</th>
<th scope="col">Limit</th>
<th scope="col">Units</th>
</tr>
</thead>
<tbody id="table-body">
</tbody>
</table>
</div>
</div>
</div>
</section>
{% endblock %}
{% block js %}
<!-- Page level plugins -->
<script src="http://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js></script>
<script src="http://cdn.datatables.net/1.10.24/js/dataTables.bootstrap4.min.js></script>
<script>
$(document).ready(function () {
$.get("airpollution_table_data", function (data) {
console.log(data)
});
})
</script>
{% endblock %}
edit Solution
I added jquery before using datatables and error has gone!:
<script src="{% static 'vendor/jquery/jquery.min.js' %}"></script>
<script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script>
<script>
$(document).ready(function () {
$.get("airpollution_table_data", function (data) {
console.log(data)
});
})
</script>
Related
got this code from a friend, we use django and bootstrap to make a rather simple site that displays job offers, until now we displayed the job offers in a row and each offer had a button "apply" that sent the resume etc.. But we would like to change that and only display one job at a time, each job would have 2 buttons "apply" and "next". We tried in a barbaric way to do all this but we have a problem, the next button works well thanks to a little javascript incorporated by my friend but the "apply" button we would like to move to the next offer after clicking on it, for now it only applies we can't get it to display the next offer, how to do? Thank you very much for simplifying your answers I am a beginner in web development, here is the code of my Django template:
{% extends 'base2.html' %}
{% load static %}
{% block title %}
Dashboard
{% endblock %}
{% block content %}
<body class="hold-transition light-mode layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper" >
<div class="content-wrapper" >
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Emplois actifs</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">Jobs</li>
</ol>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Offres d'emploi correspondant à votre profil</h3>
</div>
<h5>{% include '_messages.html' %}</h5>
<!-- /.card-header -->
<div class="card-body">
<div class="row mt-4">
{% for item in all_relevent_opened_jobs %}
<div class="col-sm-4 job-card" data-job-id="{{ item.id }}">
<div class="position-relative p-3 bg-gradient-light" style="height: 380px">
<br>
<br>
<ul>
<li><b>Catégorie</b>: {{ item.category.job_category_title}}</li>
<li><b>Titre de l'emploi</b>: {{ item.job_title}}</li>
<li><b>Description</b>: {{ item.job_description}}</li>
<li><b>Experience</b>: {{ item.required_experience}} (années)</li>
<li><b>Salaire</b>: ${{ item.salary}}</li>
<li><b>Horaires</b>: {{ item.working_hours }} heures par semaine</li>
<li><b>Ville</b>: {{ item.location }}</li>
<button class="next-job btn btn-primary">Suivant</button>
Postuler
</ul>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$('.job-card').hide();
$('.job-card').first().show();
});
</script>
<script>
$(document).ready(function(){
$('.next-job').click(function(){
$('.job-card:visible').hide().next('.job-card').show();
});
$('.apply-job').click(function(){
$('.job-card:visible').hide().next('.job-card').show();
});
});
</script>
<script>
$(document).ready(function(){
$('.next-job').click(function(){
if($('.job-card:visible').next('.job-card').length){
$('.job-card:visible').hide().next('.job-card').show();
}
});
$('.apply-job').click(function(){
if($('.job-card:visible').next('.job-card').length){
$('.job-card:visible').hide().next('.job-card').show();
}
});
});
</script>
<script>
$(document).ready(function(){
$('.job-card').not(':first').hide();
$('.next-job').click(function(){
if($('.job-card:visible').next('.job-card').length){
$('.job-card:visible').hide().next('.job-card').show();
}
else {
$('.no-more-jobs').show();
}
});
$('.apply-job').click(function(e){
e.preventDefault();
window.location = $(this).attr('href');
});
});
</script>
{% endblock %}
I am making a ecommerce website with Django framework.
I cannot make my bootstrap carousel work. Clicking on indicators and controls has no effect.
I have pulled in Bootstrap source files with NPM.
main.html
<!DOCTYPE html>
{% load static %}
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{% static 'css/main.css' %}" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<title>
{% block title %}
{% endblock title %}
</title>
</head>
<body class="mt-sm-5 mt-md-5 mt-lg-5 mt-xl-5">
<header>
<div class="container border-bottom border-primary border-1">
</div>
</header>
<section class="page-content" id="page-content">
{% block content %}
{% endblock content %}
</section>
<script src="{% static 'js/bootstrap.js' %}"></script>
</body>
</html>
product_details.html
{% extends 'main.html' %}
{% load static %}
{% block title %}
Boutique - {{ product.title }}
{% endblock title %}
{% block content %}
<div class="container">
<div class="row" >
<div id="product-carousel" class="col-sm-12 col-md-6 border border-danger carousel slide carousel-fade" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#product-carousel" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
{% if product.image2 %}
<button type="button" data-bs-target="#product-carousel" data-bs-slide-to="1" aria-label="Slide 2"></button>
{% endif %}
{% if product.image3 %}
<button type="button" data-bs-target="#product-carousel" data-bs-slide-to="2" aria-label="Slide 3"></button>
{% endif %}
</div>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="{{ product.image.url }}" class="img-fluid" alt="...">
</div>
{% if product.image2 %}
<div class="carousel-item">
<img src="{{ product.image2.url }}" class="img-fluid" alt="...">
</div>
{% endif %}
{% if product.image3 %}
<div class="carousel-item">
<img src="{{ product.image3.url }}" class="img-fluid" alt="...">
</div>
{% endif %}
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#product-carousel" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#product-carousel" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="col-sm-12 col-md-6 border border-warning">
<h3> {{ product.title }} </h3>
<h4> {{ product.price }} € </h4>
<h5> {{ product.description }} </h5>
<h6> {{ product.category }} </h6>
{% if product.stock > 0 %}
<div class="container border border-success">
<div class="row" >
<div class="col">
<label for="select-qty">Quantity</label>
</div>
<div class="col">
<select class="form-select form-select-sm" aria-label=".form-select-sm example" id="select-qty">
<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>
<div class="col">
<button id="add-to-cart-button" value="{{ product.id }}" type = "button" class="btn btn-success">Ajouter au panier</button>
</div>
</div>
</div>
{% endif %}
<div class="container">
<div class="row" >
<div class="col-sm-12 col-md-6">
<a class="btn btn-dark" href="{% url 'basket:basket_summary' %}">Panier</a>
</div>
<div class="col-sm-12 col-md-6">
<a class="btn btn-light" href="{% url 'store:all_products' %}">Voir les produits</a>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
// Add to cart
$(document).on('click', '#add-to-cart-button', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "basket:basket_add" %}',
data: {
productid: $('#add-to-cart-button').val(),
productqty: $('#select-qty option:selected').val(),
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post',
},
success: function (json) {
document.getElementById("cart-count").innerHTML = json.qty;
},
error: function (xhr, errmsg, err) {
},
});
})
</script>
<script type="text/javascript">
$(function(){
$('#product-carousel').carousel();
});
</script>
{% endblock content %}
The products have at least to images (image and image 2) and the controls and indicators show. But nothing happens when clicking on them.
EDIT
In the browser console, I have two errors.
Uncaught SyntaxError: import declarations may only appear at top level of a module
Uncaught TypeError: $(...).carousel is not a function
You are getting an Uncaught TypeError: $(...).carousel is not a function because you called that function before you loading the boostrap.js.
Give this a try, first load the boostrap.js (you can load it from your local)
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
then add your custom script
<script type="text/javascript">
$(function(){
$('#product-carousel').carousel();
});
</script>
Trying to apply infinite scrolling using Waypoints but cant seem to get it working.
I have the following scripts loaded in my base.html after downloading them and saving in my static folder:
<script src="{% static 'js/jquery-3.5.1.min.js' %}"></script>
<script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'js/infinite.min.js' %}"></script>
Then I have the following code in my template exteded from the base:
{% extends "base.html" %}
{% load static %}
{% block css %}
<link rel="stylesheet" href="{% static 'home/main.css' %}">
{% endblock css %}
{% block content %}
<br>
<div class="container status-update">
<div class="container">
<form>
<div class="input-group-lg">
<input type="text" class="form-control" value="What's new?">
</div>
<br style="height:20px">
<button type="submit" class="btn btn-primary btn-lg" name="button">Post</button>
</form>
</div>
</div>
<br>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light" style="background-color: #6298bf">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<div class="navbar-nav">
<a class="nav-link active" href="{% url 'home' %}">Activity Feed</a>
<a class="nav-link" href="{% url 'vehicle_updates' %}">Vehicle Updates<span class="sr-only">(current)</span></a>
<a class="nav-link" href="/space.html">Garage Updates</a>
</div>
</div>
</nav>
</div>
<br>
<div class="container">
<div class="primary-segments">
<h2>Activity Updates</h2>
<div class="infinite-container">
{% for post in posts %}
<div class="infinite-item">
<div class="card m-3">
<div class="card-body" style="background-color:#bdcade; padding-bottom:0px">
<div class="media mb-3">
<img src="{{ user.profile.image.url }}" class="d-block ui-w-40 rounded-circle" style="width:40px;height:auto;" alt="">
<div class="media-body ml-3">
<h5 style="color:#ffffff">{{ post.user.first_name }} {{ post.user.last_name }}</h5>
<div class="small text-muted">Yesterday</div>
</div>
</div>
</div>
{% if post.image %}
<img src="{{ post.image.url }}" class="card-img-top" alt="">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{ post.title }}</h5>
<p class="card-text">{{ post.content }}</p>
<div class="btn-group" role="group">
<button type="button" class="btn btn-secondary">Like</button>
<button type="button" class="btn btn-secondary">Comment</button>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% if page_obj.has_next %}
<a class="infinite-more-link" href="?page={{ page_obj.next_page_number }}">More</a>
{% endif %}
</div>
</div>
<script type="javascript">
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0]
});
</script>
{% endblock content %}
When I run the server and load the page, it just shows a `more' button at the bottom of the page that I can click on to take me to the next group of objects (set pagination to 3 in the view).
Doesn't look like it is throwing any errors in the console when I run the server, so I'm not sure where to look next for the problem. Any help would be much appreciated.
Figured it out.
Moved the the JS script tags from the bottom of the body up into the head and it started working. Wasn't aware of this location dependency.
I am using Bootstrap 4 radio button radio button in a flask application. and below is the snippet I used
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary">
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="twitter"/> Twitter
</label>
<label class="btn btn-outline-secondary" >
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="facebook"/> Facebook
</label>
</div>
and the javascript code
<script type="text/javascript">
function toggleElements() {
alert('hurray');
if(document.getElementBId('twitter').checked) {
document.getElementById('twitterrows').style.display = 'block';
document.getElementById('facebookrows').style.display = 'none';
}
if(document.getElementById('facebook').checked) {
document.getElementById('facebookrows').style.display = 'block';
document.getElementById('twitterrows').style.display = 'none';
}
}
</script>
Initially,I tried with simple html radio buttons and was able to trigger Javascript function toggleElements(). However, after replacing the normal radio buttons with the bootstrap radio, nothing is triggered.
Below is the entire html code
{% from 'helper/forms.html' import render_field with context %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sharjah Tourism Search Results</title>
<script src="{{ url_for('static', filename='js/jquery-3.2.1.min.js') }}"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="{{ url_for('static',filename='styles/home.css')}}"/>
<script type="text/javascript">
function toggleElements() {
alert('hurray');
if(document.getElementBId('twitter').checked) {
document.getElementById('twitterrows').style.display = 'block';
document.getElementById('facebookrows').style.display = 'none';
}
if(document.getElementById('facebook').checked) {
document.getElementById('facebookrows').style.display = 'block';
document.getElementById('twitterrows').style.display = 'none';
}
}
</script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{{ url_for('home')}}"><strong>Search</strong></a>
<button class = "navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent-7"
aria-controls="navbarSupportedContent-7" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent-7">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="{{url_for('add_url')}}">Add<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('file_render')}}">Import</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">
Websites
</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="{{ url_for('list_urls') }}">List</a>
<a class="dropdown-item" href="{{ url_for('list_crawled_websites')}}">Selected</a>
</div>
</li>
</ul>
</div>
</nav>
<!-- Header -->
<div class="container">
<br />
<div class="row">
<!-- Logo -->
<div class="col-sm">
<img class="w-50 h-60" src="{{url_for('static',filename='images/sctda_logo.jpg')}}" />
</div>
<!-- Search Bar -->
<div class="col-sm-5 searchbar">
<form action="{{url_for('fetch_results')}}" method="POST">
<div class="input-group">
<input type="search" placeholder="Search" class="form-control" name="search" id="search" value="{{data['search_term']}}" class="w-75 h-75" required>
<div class="input-group-append">
<button type="submit" class="btn btn-outline-secondary btn-sm"><i class="fa fa-search"></i></button>
</div>
</div>
</form>
</div>
</div>
<div id="container">
<div class="row">
{%set data = data['results'] %}
<div class="col-md-4">
<div class="btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary active">
<input type="radio" checked autocomplete="off"> Internal
</label>
</div>
<hr>
{% set internals = data['internal'] %}
{% if internals is defined and internals|length %}
{% for internal in internals %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ internal['title'] }}</h5>
<p class="card-text">{{ internal['description'] }}</p>
{{ internal['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
<div class="col-md-4">
{% set externals = data['external'] %}
{% if externals is defined and externals|length %}
<div class="btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary active">
<input type="radio" checked autocomplete="off"> External
</label>
</div>
<hr>
{% for external in externals %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ external['title'] }}</h5>
<p class="card-text">{{ external['description'] }}</p>
{{ external['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
<div class="col-md-4">
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary">
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="twitter"/> Twitter
</label>
<label class="btn btn-outline-secondary" >
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="facebook"/> Facebook
</label>
</div>
<hr>
(<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="twitter"/> Twitter,
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="facebook"/> Facebook)
<div id="twitterrows">
{% set tweets = data['twitter'] %}
{% if tweets is defined and tweets|length %}
{% for tweet in tweets %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ tweet['title'] }}</h5>
<p class="card-text">{{ tweet['description'] }}</p>
{{ tweet['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
<div id="facebookrows">
{% set posts = data['facebook'] %}
{% if posts is defined and posts|length %}
{% for post in posts %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ post['title'] }}</h5>
<p class="card-text">{{ post['description'] }}</p>
{{ post['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
</div>
</div>
</div>
<center>Developed by School of Information Technology Team,Skyline University College</center>
</body>
</html>
I strongly suspect with the order of scripts being called under the head tag. Can someone help me to fix this please.
make sure you have included the correct version of bootstrap. Please check if there is any error in the browser console.
https://getbootstrap.com/docs/4.4/components/input-group/#checkboxes-and-radios.
I am suspecting that the javascript click is not properly binded to the click event.
I fixed it by replacing the three script tags in the above html page with the below
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
How to create a running total using javascript in django form.
This is my model:
class Contra(models.Model):
date = models.DateField(default=datetime.date.today)
account = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='contraledgers')
class Particularscontra(models.Model):
contra = models.ForeignKey(Contra,on_delete=models.CASCADE,related_name='contras')
particular = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='particularcontra')
amount = models.DecimalField(max_digits=10,decimal_places=2,null=True)
This is my form:
class ContraForm(forms.ModelForm):
class Meta:
model = Contra
fields = ('date','account')
widgets = {
'date': DateInput(),
}
def __init__(self, *args, **kwargs):
super(ContraForm, self).__init__(*args, **kwargs)
self.fields['account'].widget.attrs = {'class': 'form-control select2',}
class ParticularscontraForm(forms.ModelForm):
class Meta:
model = Particularscontra
fields = ('particular','amount')
def __init__(self, *args, **kwargs):
super(ParticularscontraForm, self).__init__(*args, **kwargs)
self.fields['particular'].widget.attrs = {'class': 'form-control select2',}
self.fields['amount'].widget.attrs = {'class': 'form-control',}
Contra_formSet = inlineformset_factory(Contra, Particularscontra,
form=ParticularscontraForm, extra=6)
This
I tried this previously but was unsuccessful:
{% block content %}
<div class="content-wrapper">
<!-- <div class="container"> -->
<section class="content-header">
<!-- <div class="col-md-12 col-md-offset-4"> -->
<h1>
<strong>Company : {{company_details.Name}}</strong>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<!-- <li>Company list</li> -->
<li class="">Company list</li>
<li class="active">Create Simple Unit</li>
</ol>
<!-- </div> -->
</section>
<section class="content">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<!-- Horizontal Form -->
<div class="box">
<div class="box-header with-border">
{% if not form.instance.pk %}
<h3 class="box-title"><strong>Create Contra</strong></h3>
{% else %}
<h3 class="box-title"><strong>Update Contra</strong></h3>
{% endif %}
</div>
<!-- /.box-header -->
<!-- form start -->
<form method="POST" class="form-horizontal">
{% csrf_token %}
<div class="row">
<div class="col-md-12">
<div class="box box-success">
<div class="box-body form-responsive no-padding">
<br>
<br>
<div class="col-md-2">
<div class="form-group">
<label for="PAN1" class="col-md-4 control-label">Account<i class="material-icons" style="font-size:16px;color:red">*</i></label>
<div class="col-md-8">
{{ form.account }}
</div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="State1" class="col-md-4 control-label">Date<i class="material-icons" style="font-size:16px;color:red">*</i></label>
<div class="col-md-8">
{{form.date}}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="box box-success">
<div class="box-body table-responsive no-padding">
<table class="table">
{{ contras.management_form }}
<thead>
<tr>
<th class="col-md-6">Particulars<i class="material-icons" style="font-size:16px;color:red">*</i></th>
<th class="col-md-6">Amount<i class="material-icons" style="font-size:16px;color:red">*</i></th>
</tr>
</thead>
<tbody id="calculate">
{% for form in contras.forms %}
<tr class='{% cycle "row1" "row2" %} formset_row'>
<td class="col-md-6">{{ form.id }} {{ form.particular}}</td>
<td class="col-md-6 amounts">{{ form.amount}}</td>
</tr>
{% endfor %}
</tbody>
<tr>
<td class="col-md-6"></td>
<td class="col-md-6" id="totaled"><input type="text" name="total"></td>
</tr>
</table>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default" type="reset" value="Reset">Reset</button>
{% if not form.instance.pk %}
<button type="submit" class="btn btn-info pull-right" value="Submit">Create</button>
{% else %}
<button type="submit" class="btn btn-info pull-right" value="Submit">Update</button>
{% endif %}
</div>
<!-- /.box-footer -->
</form>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'add contra',
deleteText: 'remove',
prefix: 'contras'
});
</script>
<script type="text/javascript">
$(document).ready(function() {
let tableInstance = $('#calculate td.amounts');
let totals = 0;
tableInstance.each(function() {
totals = totals + Math.floor($(this).text() * 100) / 100;
});
$(".totaled :input").val(totals);
});
</script>
</section>
</div>
{% endblock %}
This is the javascript code I tried:
<script type="text/javascript">
$(document).ready(function(e){
$('#calculate tbody').change(function(){
var totals = 0;
$(".amounts").each(function(){
totals = totals + parseInt($(this).val());
})
$(".totaled").val(totals);
});
});
</script>
I am using inline formset in my template I want to display the running total of all the amount given in my inline form..
How is that possible to do it in django?
any guess?
Thank you
Not sure if someone is still looking for an answer to this. This is the code I used. 'total' is the id of a span element, where the running total is shown.
$("input.numberinput").change(function(){
sum=0
$("input.numberinput").each(function(){
sum += parseInt($(this).val());
})
$('#total').text(sum);
})
Select each td class amounts, iterate and add over them.
$(document).ready(function() {
let tableInstance = $('#calculate td.amounts');
let totals = 0;
tableInstance.each(function() {
totals = totals + Math.floor($(this).text() * 100) / 100;
});
$(".totaled :input").val(totals);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<table class="table" id="calculate">
<thead>
<tr>
<th class="col-md-6">Particulars <i class="material-icons" style="font-size:16px;color:red">*</i></th>
<th class="col-md-6">Amount <i class="material-icons" style="font-size:16px;color:red">*</i></th>
</tr>
</thead>
<tbody>
<tr class="row1 formset_row">
<td class="col-md-6">1</td>
<td class="col-md-6 amounts">5.2</td>
</tr>
<tr class="row2 formset_row">
<td class="col-md-6">2</td>
<td class="col-md-6 amounts">5.5</td>
</tr>
<tr>
<td class="col-md-6"></td>
<td class="col-md-6 totaled"><input type="text" name="total"></td>
</tr>
</tbody>
</table>