Django submit button not working on Ajax request - javascript

I am building a website which users can create posts and comment on it, however, after clicking the submit button in the post_detail.html template to submit the comment, nothing happens and I cannot een see an error. I am using jQuery to submit the form
this is my post_detail view:
#login_required
def post_detail(request, id):
data = dict()
post = get_object_or_404(Post, id=id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(False)
comment.post = post
comment.name = request.user
comment.save()
comments = post.comments.all()
data['form_is_valid'] = True
data['comments'] = render_to_string('home/posts/post_detail.html', { 'comments':comments }, request=request)
else:
data['form_is_valid'] = False
else:
form = CommentForm
comments = post.comments.all()
context = {
'form': form,
'comments': comments,
'post': post
}
data['html_data'] = render_to_string('home/posts/post_detail.html', context,request=request)
return JsonResponse(data)
this is my post_detail.html template:
{% load crispy_forms_tags %}
{% load static %}
<script src="{% static 'js/comment.js' %}"></script>
<div class="modal-header-sm">
<button type="button" class="close mx-2" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="card mt-3 rounded-0 mb-3" style="max-width: 100rem !important;">
<div class="card-body text-dark">
<div class="d-flex">
<img class="img-create-post rounded-circle mr-2" style="width: 50px;height: 50px;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg"
alt="Profile image">
<span class="align-text-top"><a class="mr-2 text-dark font-weight-bolder" href="#">{{ post.author.first_name }} {{ post.author.last_name }} </a><br><p class="font-weight-light text-muted">{{ post.title }}</p></span>
<div class="float-right text-right ml-auto">
<p class="text-muted small" style="font-size: 0.7rem;">{{ post.date_posted|date:"F d, Y" }}</p>
</div>
</div>
<p class="card-text">{{ post.content }}</p>
</div>
<div class="card-footer" style="height: 5rem;">
<a class="mx-1 small" data-href='{{ post.get_api_like_url }}' data-likes='{{ post.likes.count }}' href='{{ post.get_like_url }}'><i class="fas fa-thumbs-up"></i> Like</a>
<hr class="my-1">
<p class="text-muted small">
{% if post.author == request.user %}
<button class="btn btn-sm text-muted show-form-delete ml-auto" data-url="{% url 'home:post-delete' post.id %}" style="font-size: small;" style="height: 0rem;">Remove</button>
{% endif %}
<small class="float-sm-right">
{{ post.likes.count }} Likes, {{ post.comments.count }} Comments
</small>
</p>
</div>
<div class="card-body">
<div class="row">
<img class="img-create-post rounded-circle mr-2" style="width: 40px;height: 40px;" src="{{ request.user.image }}" alt="Profile image">
<form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
{% csrf_token %}
<div class="row ml-1">
{{ form | crispy }}
<button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button>
</div>
</form>
</div>
<hr>
</div>
<div id="post-linked-comments">
<div>
{% include 'home/posts/post_comment.html' %}
</div>
</div>
</div>
the post_comment.html template for your reference however it is most likely not the issue:
<ul class="list-group list-group-flush">
{% for comment in comments %}
<li class="list-group-item">
<div class="d-flex">
<img class="img-create-post rounded-circle mr-1" style="width: 20px;height: 20px;" src="{{ comment.name.image }}"
alt="Profile image">
<span class="align-text-top font-weight-bolder">{{ comment.name.first_name }}
<p class="text-muted small mx-2" style="font-size: 0.7rem;">{{ comment.created_on|date:"F d, Y at: f A" }}</p><br>
<p class="font-weight-light">{{ comment.body }}</p></span>
</div>
</li>
{% empty %}
<li class="list-group-item">
<div class="d-flex">
<p class="font-weight-lighter text-muted">No comments to show</p>
</div>
</li>
{% endfor %}
</ul>
and finally my javascript code in comment.js:
$(document).ready(function(){
var ShowForm = function(e){
e.stopImmediatePropagation();
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType:'json',
beforeSend: function(){
$('#modal-post-detail').modal('show');
},
success: function(data){
$('#modal-post-detail .modal-content').html(data.html_data);
}
});
};
var SaveForm = function(e){
e.stopImmediatePropagation();
var form = $(this);
$.ajax({
url: form.attr('data-url'),
data: form.serialize(),
type: form.attr('method'),
dataType: 'json',
success: function(data){
if(data.form_is_valid){
$('#post-linked-comments div').html(data.comments);
alert('Comment added')
} else {
$('#modal-post-detail .modal-content').html(data.html_data)
}
}
})
return false;
}
//adding a comment
$('.comment-post-btn').click(ShowForm);
$('.post-detail-clickable-details-view').click(ShowForm);
$('#modal-post-detail').on("submit",".post-comment-form",SaveForm)
});
There is no issue with getting the Javascript file as the post_detail modal pops up fine, however after clicking on the add button nothing happens.
Thanks for all the help in advance.
EDIT: Button should be added inside the form but now NoReverseMatchException is being thrown after clicking on 'Add' button:
New Form:
<form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
{% csrf_token %}
<div class="row ml-1">
{{ form | crispy }}
<button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button>
</div>
</form>
urls.py:
path('post/<int:id>/', views.post_detail, name='post-detail'),
Error:
django.urls.exceptions.NoReverseMatch: Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['home/post/(?P<id>[0-9]+)/$']
SOLVED: I managed to solve the issue myself. it was from my views. I was sending the comments to the wrong html template. Below you can see the corrected view for the template.
#login_required
def post_detail(request, id):
data = dict()
post = get_object_or_404(Post, id=id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(False)
comment.post = post
comment.name = request.user
comment.save()
comments = post.comments.all()
data['form_is_valid'] = True
#data['comments'] = render_to_string('home/posts/post_detail.html', { 'comments':comments }, request=request)
#corrected code below
data['comments'] = render_to_string('home/posts/post_comment.html', { 'comments':comments }, request=request) else:
data['form_is_valid'] = False
else:
form = CommentForm
comments = post.comments.all()
context = {
'form': form,
'comments': comments,
'post': post
}
data['html_data'] = render_to_string('home/posts/post_detail.html', context,request=request)
return JsonResponse(data)

I believe nothing is happening since the submit button is not defined within any form tags.
From the code in post_detail.html the button tags are outside the form tags.
<div class="row">
<img class="img-create-post rounded-circle mr-2" style="width: 40px;height: 40px;" src="{{ request.user.image }}" alt="Profile image">
<form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
{% csrf_token %}
<div class="moda-body">
{{ form | crispy }}
</div>
</form>
<button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button>
</div>
The button tag should be placed before the closing tag of the form.
<div class="row">
<img class="img-create-post rounded-circle mr-2" style="width: 40px;height: 40px;" src="{{ request.user.image }}" alt="Profile image">
<form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
{% csrf_token %}
<div class="moda-body">
{{ form | crispy }}
</div>
<button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button>
</form>
</div>

Related

My form redirects the page to the API url used on the form (action="some url") after submitting, how to fix this? Django VanillaJS

This is what my page looks like:
I have a sidebar which can change the contents of the page depending on the button clicked. When I click on About the page will look like this:
So I made this with Vanilla JS using inner.HTML.
PROBLEM: When I refresh the page, meaning the inner.HTML is not happening yet because I never clicked any buttons on the sidebar yet. My form submits properly and it does not redirect me to the API url used on the form. But, when I tried to click the About button and click Home button and try to submit the form again, it redirects me now to the API page used on the form. My guess is, there is something wrong with my vanillajs using inner.HTML.
CODE looks like this:
HTML:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block script %}
<script type="text/javascript" src="{% static 'js/cms/cms.js' %}"></script>
{% endblock %}
{% block style %}
<link rel="stylesheet" type="text/css" href="{% static 'css/cms.css' %}">
{% endblock %}
{% block content %}
<div class="container">
<div class="sticky-sidebar-page">
<div class="sidebar">
<h3>Manage Site Contents</h3>
<div class="list-group">
<button class="list-group-item list-group-item-action active" aria-current="true" onClick="showHomeContent()" id="homeButton">Home</button>
<button class="list-group-item list-group-item-action" aria-current="true" onClick="showAboutContent()" id="aboutButton">About</button>
Contact Us
Sample Page
A disabled link item
</div>
</div>
<div class="sandbox">
<div class="page-content" id="page-content">
<!-- SCHOOL LOGO -->
<div class="card" id="school-logo">
<div class="card-body">
<h5>School Logo</h5>
<small>On display:</small> <br>
<img src="{{logo.image.url}}" id="img" class="card-img-top" alt="..." style="max-width: 10rem; max-height: 10rem;"> <br>
<small>Change:</small>
<form action="{% url 'changelogo' %}" method="POST" enctype="multipart/form-data" id="logo-form">
{% csrf_token %}
<div class="input-group mb-3">
<input type="file" name="image" class="form-control" required id="inputGroupFile02">
<button type="submit" class="input-group-text" for="inputGroupFile02">Upload
</button>
</div>
</form>
</div>
</div>
<!-- HOME CAROUSEL -->
<div class="card">
<div class="card-body">
<h5>Home Carousel</h5>
<small>On display:</small><br>
{% for pic in carouselpics %}
<img src="{{pic.image.url}}" class="card-img-top" alt="..." style="max-width: 15rem; max-height: 15rem;"> <br>
Label: {{pic.label}} <br>
Content: {{pic.content}}<br>
<span style="font-size: 20px;">
<span style="color: red;">
<i class="fas fa-trash-alt"></i>
</span>
<span style="color:brown">
<i class="far fa-edit"></i>
</span>
</span>
<br>
<hr>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
const csrftoken = "{{csrf_token}}"
//home contents
var changeLogoUrlView = "{% url 'changelogo' %}"
var schoolLogo = "{{logo.image.url|safe}}";
</script>
JS:
const pageContent = document.getElementById('page-content')
// Getting Home Page Contents
function getLogo(){
var url = "http://localhost:8000/web-content/api/changelogo/"
fetch(url)
.then((response) => response.json())
.then(function(data){
pageContent.innerHTML = `
<div class="card" id="school-logo">
<div class="card-body">
<h5>School Logo</h5>
<small>On display:</small> <br>
<img src="${data[0].image}" id="img" class="card-img-top" alt="..." style="max-width: 10rem; max-height: 10rem;"> <br>
<small>Change:</small>
<form action="http://localhost:8000/web-content/api/changelogo/" method="POST" enctype="multipart/form-data" id="logo-form">
<input type="hidden" name="csrfmiddlewaretoken" value="${csrftoken}" >
<div class="input-group mb-3">
<input type="file" name="image" class="form-control" required id="inputGroupFile02">
<button type="submit" class="input-group-text" for="inputGroupFile02">Upload
</button>
</div>
</form>
</div>
</div>
`
})
}
function showHomeContent(){
if ( document.getElementById("homeButton").className.match(/(?:^|\s)active(?!\S)/) ){
return;
}else{
document.getElementById('homeButton').classList.add('active')
}
if ( document.getElementById("aboutButton").className.match(/(?:^|\s)active(?!\S)/) ){
document.getElementById("aboutButton").classList.remove('active')
}
pageContent.innerHTML = ""
getLogo()
}
function showAboutContent(){
if ( document.getElementById("aboutButton").className.match(/(?:^|\s)active(?!\S)/) ){
return;
}else{
document.getElementById('aboutButton').classList.add('active')
}
if ( document.getElementById("homeButton").className.match(/(?:^|\s)active(?!\S)/) ){
document.getElementById("homeButton").classList.remove('active')
}
pageContent.innerHTML = `
this is about content
`
}
// formsssssss
// change logo
var logoform = document.getElementById('logo-form')
logoform.addEventListener('submit', function(e){
e.preventDefault()
let input = document.getElementById('inputGroupFile02');
let data = new FormData();
data.append('image',input.files[0]);
var url = "http://localhost:8000/web-content/api/changelogo/"
fetch(url,{
method: "POST",
headers: {
"X-CSRFToken": csrftoken,
},
body:data
})
.then((response) => response.json())
.then(function(data){
getLogo()
logo = document.getElementById('logo-div')
logo.innerHTML = ""
logo.innerHTML = `<img src="${data.image}" alt="no image provided" style="max-width: 7rem; max-height: 7rem;">`
})
})
views.py:
this is the view I am using to for the change logo form where the problem happens when submitting after the page is rendered with inner.HTML:
class ChangeLogo(generics.ListCreateAPIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated, IsAdminUser]
serializer_class = SchoolLogoSerializer
queryset = SchoolLogo.objects.all()

Ajax success function not working: Django JSONResponse not sending

In the code below, I am using onclick (I know it may not be the best practice but for my particular situation I think it works best) to activate an ajax call to dynamically update the content on my Django template. As of now, the data is going to the back-end, and the Comment object is being created.
However, when returning a JSONResponse, the template is not using the data from this JSONResponse to update the page in any way. I have tried testing with alerts but to no avail. I am new to JS so I would love a little help! Thank you very much.
Django View:
def sochome(request, oid):
society = Society.objects.filter(id=oid).first()
membership = SocietyMembership.objects.get(member=request.user, society=society)
response_data = {}
if request.method == 'POST':
postID = request.POST.get('post_id')
comment_content = request.POST.get('comment')
response_data['post_id'] = postID
response_data['comment'] = comment_content
post = SocPost.objects.filter(id=postID).first()
SocComment.objects.create(post=post, author=request.user, content=comment_content)
# print(response_data, file=sys.stderr)
# print("SUCCESS JSON RESPONSE TO CLIENT SIDE", file=sys.stderr)
return JsonResponse(response_data)
context = {
'membership': membership,
'posts': society.posts.all().order_by('-date_posted')
}
return render(request, 'blog/sochome.html', context)
HTML:
< script type = "text/javascript" >
function update_comment(post_id) {
$.ajax({
type: 'POST',
url: "{% url 'blog-sochome' oid=membership.society.id%}",
data: {
'post_id': post_id,
'comment': document.getElementById(post_id.toString()).value
},
dataType: 'text',
success: function(data) {
alert("ajax completed ");
}
});
} <
/script>
<div id="{{post.id}}-comment-section" class="mb-3 pr-5 pt-4 pb-2 bg-light shadow-sm border-light" style="border-bottom-left-radius: 0.5rem; border-bottom-right-radius: 0.5rem;">
<div class="col-sm-12 pl-5 pb-5">
<form class="form-inline" method="POST" action="" style="display:flex" id="comment"> {% csrf_token %}
<input id="{{post.id}}" type="search" name="comment" placeholder="New comment" class="form-control mr-sm-2 p-4" style="flex-grow:1;">
<button name="post_id" class="btn btn-info my-2 my-sm-0 " value="{{post.id}}" onclick="update_comment({{post.id}})"> Post </button>
</form>
</div>
{% for comment in post.comments.all %}
<div class="row">
<div class="col-xs-1 offset-1 pl-4">
<img class="rounded-circle comment-image" src="{{ comment.author.profile.image.url }}" />
</div>
<div class="col-xs-4">
<a class="mr-2 comment-author-name" href="#">{{ comment.author.first_name }} {{ comment.author.last_name }}</a>
<small class="text-muted comment-time"><br>{{ comment.date_posted|date:"F d, Y" }}</small>
</div>
</div>
<div class="row">
<div class="col-sm-12 offset-1">
<p class="comment-content">{{ comment.content }}</p>
</div>
</div>
{% empty %}
<div class="px-5">
<p>No comments for this post.</p>
</div>
{% endfor %}
</div>
{% endfor %}

django error: cart.js:4 Uncaught TypeError: updateBtns[i].addEventListner is not a function at cart.js:4

I have never worked with js until now and i keep getting this error
cart.js:4 Uncaught TypeError: updateBtns[i].addEventListner is not a function
at cart.js:4
I have searched it and none of the answers that i used helped.
cart.js
var updateBtns = document.getElementsByClassName('update-cart')
for (var i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListner('click', function(){
var productId = this.dataset.products
var action = this.dataset.action
console.log('productId: ', productId, 'action: ', action)
})
}
store.html
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<form method="GET" action=".">
<div class="row">
<div class="column">
<button type='submit' class='btn btn-primary btn2'>Search</button>
</div>
<div class="column">
<input type="text" name="search" class="form-control" placeholder="search" />
</div>
</div>
</form>
</div>
<div class="row">
{% for product in products %}
<div class="col-lg-4">
<img class="thumbnail" src="{{ product.imageURL }}">
<div class="box-element product">
<h6><strong>{{ product.name }}</strong></h6>
<hr>
<button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>
<a class="btn btn-outline-success" href="#">View</a>
<h4 style="display: inline-block; float: right"><strong>R{{ product.price|floatformat:2 }}</strong></h4>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
part of store.html
<button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>
i am using python django and trying to make a cart system for my ecom store

Update only one element inside same div classes using jQuery

I am trying to update the DOM, whenever a user likes a post and displays the number of likes on a post. However, I realized my function will update all the classes on the pages and not only the certain post being liked (When a user clicks on thmbs up, all the thumbs up buttons change to dumbs down)
my function for changing the like:
function like_post() {
// newly added
$('#like-section #likeBtn').on("click", function (e) {
e.preventDefault();
if($("#like-section #likeBtn i").hasClass("fa-thumbs-up")){
($("#like-section #likeBtn i").removeClass("fa-thumbs-up"))
($("#like-section #likeBtn i").addClass("fa-thumbs-down"))
} else {
($("#like-section #likeBtn i").removeClass("fa-thumbs-down"))
($("#like-section #likeBtn i").addClass("fa-thumbs-up"))
}
});
// end
}
my posts HTML template in Django:
{% load static %}
<link rel="stylesheet" href="{% static 'css/post/style.css' %}">
<script src="{% static 'js/like-api.js' %}"></script>
<script src="{% static 'js/post.js' %}"></script>
{% for post in posts %}
<script>
$(document).on('click', '.post-detail-clickable-details-view', function () {
var url = $(this).attr("data-url")
document.location.href = url
});
</script>
<div class="row ml-2">
<div class="col-sm-2">
<div class="float-right mb-3 mt-3">
<div>
<img class="img-create-post rounded-circle mr-2" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg"
alt="Profile image">
</div>
<div>
<p class="text-muted post-card-date small mr-2">{{ post.get_created_on }} ago</p>
</div>
</div>
</div>
<div class="col-md-10" style="margin-left: -1.6rem;">
<div class="card rounded-0 mb-3 mt-3">
<div class="card-header bg-transparent" style="height: 3rem;">
<h5 style="margin-bottom: 0px;">
<a class="text-dark" style="text-decoration: none;" href="{% url 'home:post-detail' post.guid_url %}">{{ post.title }}</a>
<span class="small text-muted">#{{ post.author.username }}</span>
</h5>
</div>
<div class="card-body post-detail-clickable-details-view text-dark" data-url="{% url 'home:post-detail' post.guid_url %}"
style="margin-top:-0.5rem;">
<a id="post-detail-view-link" href="{% url 'home:post-detail' post.guid_url %}"></a>
<p class="mr-1 text-dark font-weight-bolder">{{ post.author.first_name }} {{ post.author.last_name }}</p>
<p class="card-text pt-2" style="margin-top: -0.9rem;">{{ post.content }}</p>
</div>
<hr style="margin: 0;">
<div class="d-flex align-items-center justify-content-between" >
<div class="row mx-1">
<div id="like-section" class="px-1">
{% include 'home/posts/likes.html' with post=post %}
</div>
<div class="px-1">
<a class="btn btn-md" href="{% url 'home:post-detail' post.guid_url %}">
<span class="text-secondary">
<i class="fas fa-comment"></i> {{ post.comments.count }}
</span>
</a>
</div>
</div>
<div>
<a class="btn btn-md" href="#">
<span class="text-secondary">
<i class="fas fa-share-square"></i>
</span>
</a>
</div>
</div>
</div>
</div>
</div>
{% empty %}
<div class="d-flex justify-content-center">
<h5 class="h5 font-weight-lighter my-3 text-muted">No posts to show</h5>
</div>
{% endfor %}
my likes.html:
{% load static %}
<!-- static file were here -->
{% if request.user.is_authenticated %}
<script src="{% static 'js/post.js' %}"></script>
<script src="{% static 'js/comment.js' %}"></script>
<form action="{% url 'home:post-like' post.id %}" method="POST">
{% csrf_token %}
{% if request.user in post.likes.all or is_liked %}
<button type="submit" id="likeBtn" data-url="{% url 'home:post-like' post.guid_url %}" data-token="{{ csrf_token }}" name="post_id" value="{{ post.id }}" class="btn btn-md">
<span class="text-secondary">
<i class="fas fa-thumbs-down"></i>
<span id="like-count">
{{ post.likes.count }}
</span>
<input type="hidden" id="input-like-count" value=" {{ post.likes.count }} " />
</span>
</button>
{% else %}
<button type="submit" id="likeBtn" data-url="{% url 'home:post-like' post.guid_url %}" data-token="{{ csrf_token }}" name="post_id" value="{{ post.id }}" class="btn btn-md">
<span class="text-secondary">
<i class="fas fa-thumbs-up"></i>
<span id="like-count">
{{ post.likes.count }}
</span>
<input type="hidden" id="input-like-count" value=" {{ post.likes.count }} " />
</span>
</button>
{% endif %}
</form>
<div class="modal fade" id="modal-post-detail">
<div class="modal-dialog modal-dialog-scrollable modal-md adjusted-modal-detail">
<div class="modal-content"></div>
</div>
</div>
{% endif %}
my plan is to change the display for a user so there is no need to refresh the page and update the number of counts as well before refreshing the page. But currently, all the #likeBtn elements are being updated and not the one for the single post. How can I update the button of the post being liked only?
EDIT: I updated my jQuery to this, and it's still not working:
$('#like-section #likeBtn').on("click", function (e) {
e.preventDefault();
if($(this).find("#i").hasClass("fa-thumbs-up")){
($(this).find("i").removeClass("fa-thumbs-up").addClass("fa-thumbs-down"))
} else {
($(this).find("i").removeClass("fa-thumbs-down").addClass("fa-thumbs-up"))
}
});
EDIT: jsfiddle link: https://jsfiddle.net/mf0xvpho/1/
This seems to be working now
Consider the following example.
Fiddle: https://jsfiddle.net/Twisty/2hg60be3/13/
HTML
<div class="like-section">
<button type="submit" class="likeBtn btn btn-md">
<span class="text-secondary">
<i class="red">Button</i>
<span class="like-count">
3
</span>
</span>
</button>
</div>
<div class="like-section">
<button type="submit" class="likeBtn btn btn-md">
<span class="text-secondary">
<i class="blue">Button</i>
<span class="like-count">
2
</span>
</span>
</button>
</div>
<div class="like-section">
<button type="submit" id="likeBtn" class="btn btn-md">
<span class="text-secondary">
<i class="red">Button</i>
<span class="like-count">
1
</span>
</span>
</button>
</div>
JavaScript
$(function() {
$('.like-section').on("click", ".likeBtn", function(e) {
var like_count = parseInt($(".like-count", this).text());
e.preventDefault();
if ($("i", this).hasClass("blue")) {
like_count++;
$("i", this).removeClass("blue").addClass("red");
$(".like-count", this).text(like_count);
} else {
like_count--;
$("i", this).removeClass("red").addClass("blue");
$(".like-count", this).text(like_count);
}
});
});
Using classes will allow you to group elements. You can use .find() or shorthand, $("i", this). It's the same as $(this).find("i"), just shorter.

How to make all the delete href tags make work with java scripts if clicked in Django

I have written a java script for the conformation box before deleting the comments. If user clicks delete, it should pop the box for delete conformation. If i have series of comments of same user, as i am printing the comments in loop the java script logic is staying with the first delete comment itself until i delete it. If i say no, and try to delete second comment, the java script logic is not function. Can any one help me with this issue. Should i need to place the java script logic some where else in the code. Does that recognize?
<div class="container">
<h2 class="text-center">User Comments</h2>
{% for comment in comments%}
<p class="text-secondary text-center">{{ comment.created }}</p>
<p> {{ comment.body }} </p>
{% if comment.user == request.user.username %}
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'comment-update' comment.id %}">Update Comment</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" id="delete-object" >Delete Comment
<script type="text/javascript">
document.getElementById("delete-object").onclick = function(){
if (confirm('Delete the comment')){
alert('hi');
#Link to delete comment}}
</script>
{% endif %}
You are assigning the same id to multiple a tags. The id must be unique in the document.
Try with someting like
<div class="container">
<h2 class="text-center">User Comments</h2>
{% for comment in comments%}
<p class="text-secondary text-center">{{ comment.created }}</p>
<p> {{ comment.body }} </p>
{% if comment.user == request.user.username %}
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'comment-update' comment.id %}">Update Comment</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" data-action="delete-object" >Delete Comment
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
deleteLinks = document.querySelectorAll('[data-action="delete-object"]')
deleteLinks.forEach(link => {
link.addEventListener('click', function() {
if (confirm('Delete the comment')) {
alert('hi')
# link to the comment
}
})
})
})
</script>
{% endif %}
{% endfor % }

Categories

Resources