How to change contents on clicking the selected div using Javascript? - javascript

I am new to Javascript. I wish to change the contents of div on selecting a particular div element.
If I select a div, the text associated with that div contents only should display. I am using a loop to display the contents. It's like a chat application. If a user clicks on a contact the messages associated with that user should display. I am using a loop to display messages and users.
What I have tried is:
Twig code:
{% set msg = query().from('messages').get() %}
{% set to_add =to_name %}
{% set to_details = query().from('users_users').where('id', to_add).get() %}
<div class="container">
<h3 class=" text-center">Messaging</h3>
<div class="messaging">
<div class="inbox_msg">
<div class="inbox_people">
<div class="headind_srch">
<div class="recent_heading">
<h4>{{auth_user().first_name}}</h4>
</div>
<div class="srch_bar">
<div class="stylish-input-group">
<input type="text" class="search-bar" placeholder="Search" >
<span class="input-group-addon">
<button type="button"> <i class="fa fa-search" aria-hidden="true"></i> </button>
</span> </div>
</div>
</div>
<div class="inbox_chat">
{% set newArray = [] %}
{% for msg in msg_details %}
{% if msg.to_name not in newArray %}
<div class="chat_list active_chat" onclick=viewMessage(this)>
<div class="chat_people">
<div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>
<div class="chat_ib">
<h5>{{msg.to_name}} <span class="chat_date">{{msg.time}}</span></h5>
</div>
</div>
</div>
{% set newArray = newArray|merge([msg.to_name]) %}
{% endif %}
{% endfor %}
</div>
</div>
<div class="mesgs">
<div class="msg_history">
<div class="incoming_msg">
<div class="incoming_msg_img">
<img src="https://ptetutorials.com/images/user-profile.png" alt="sunil">
</div>
<div class="received_msg">
<div class="received_withd_msg">
<p>{{msg.message}}</p>
<span class="time_date">{{msg.time}}</span></div>
</div>
</div>
<div class="outgoing_msg">
<div class="sent_msg">
<p></p>
<span class="time_date"></span> </div>
</div>
</div>
</div>
</div>
</div></div>
Javascript code:
<script>
function copyText(elementId){
var x = document.getElementById(elementId).textContent;
if(document.getElementById('select-text').value.length == 0)
{
document.getElementById("btn").disabled = false;
document.getElementById(elementId).style.backgroundColor = "lightblue";
document.getElementById('select-text').focus();
document.getElementById('select-text').value += x;
}
else{
document.getElementById('select-text').readOnly = true;
}
}
</script>
What my output looks like
Output
My output shows all the messages, I want to show only the particular user message. How to do so?
What my table looks like:
Table

First of all you have to fetch the data from your table using a query something like to ensure you will get one record from each from_id.
SELECT * FROM msg GROUP BY from_id;
Then you can loop in twig to create the left side elements like,
{% for distinctMsg in distinctMsgs %}
<div class="chat_list active_chat" data-userId="{{ distinctMsg.fromId }}">
<div class="chat_people">
<div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>
<div class="chat_ib">
<h5>{{distinctMsg.to_name}} <span class="chat_date">{{distinctMsg.time}}</span></h5>
</div>
</div>
</div>
{% endfor %}
Then in your javascript:-
$(".chat_list").on("click", function(){
// have a look here https://stackoverflow.com/questions/5309926/how-can-i-get-the-data-id-attribute
var userId = $(this).data( "userId" );
// Maybe display a loading icon in the right side div
$.ajax({
type: "POST",
url: "/api/msg/user/history", // your controller url
dataType: 'json',
headers: {
// if you have any headers to set
"Authorization": "Bearer {{ token }}"
},
data:{
"userId" : userId
}
})
.done(function (response) {
// stop displaying the loading icon
// process the response and display message history in right side
})
.fail(function (xhr, status, error) {
// show proper error message
});
});
NOTE: You will have to have jQuery in your page for Ajax functions to work.

Related

Django AJAX Infinite Scroll Error on page reload

I'm trying to implement infinite scroll with django and jquery(Waypoint).
I have a ListView with a pagination of 5, but when waypoint loads second page, AJAX requests are no longer performed so I added the AJAX function on the onAfterPageLoad which helps bring back AJAX function to the newly loaded page.
That's fine, but then it introduces a bug to my code making the page loaded initially (First Page) no longer perform AJAX functions very well. It makes AJAX on the first page run 3 times if I just loaded a third page and makes AJAX on the second page run twice and so on depending on the number of pages loaded already.
I don't know if there are any cool ways to achieve this because I tried using just jquery without waypoint, but still get same errors as I get when using just waypoint making it an error. This is kinda tricky so far.
{% extends "base.html" %}
{% block content %}
{% load static %}
<div class="container" style="max-width:700px">
<div class="px-3 pt-md-5 pb-md-4 mx-auto text-center">
<h1 class="display-4">All Groups</h1>
<p class="lead">List of groups</p>
</div>
<div class="">
<div class="row infinite-container">
{% for group in groups %}
<div class="col-md-12 infinite-item">
<!-- <img class="img-fluid" src="https://picsum.photos/700"> -->
<a class="text-dark" href="{{ group.get_absolute_url }}">
<div class="card mb-4 box-shadow">
<div class="card-body">
<h2 style="font-size:18px;font-weight:bold;min-height:42px;">
{{group.name|truncatechars:50}}</h2>
<div class="d-flex justify-content-between align-items-center">
<small class="text-muted">{{group.owner}}</small>
<small class="text-muted">{{group.date_created}}</small>
</div>
<p><a class='follow-btn' data-href='{{ group.get_group_follow_api_url }}'
data-likes='{{ page.likes.count }}'
href='{{ group.get_group_follow_url }}'>{{ group.follows.count }}
{% if request.user.profile in group.follows.all %}
Unfollow
{% else %}
Follow
{% endif %}
</a></p>
</div>
</div>
</a>
</div>
{% endfor %}
</div>
<!-- Comment for loading spinner -->
{% comment %}
<div class="d-flex d-none position-fixed" style="top:35vh;left:46vw">
<button class="btn btn-primary loading">
<span class="spinner-border spinner-border-sm"></span>
Loading...
</button>
</div>
{% endcomment %}
<!-- End of comment for loading spinner -->
<div class="row">
<div class="col-12">
{% if page_obj.has_next %}
<a class="infinite-more-link" href="?page={{ page_obj.next_page_number }}"></a>
{% endif %}
</span>
</div>
</div>
</div>
</div>
<script src="{% static "js/jquery.waypoints.min.js" %}"></script>
<script src="/static/js/infinite.min.js"></script>
<script>
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0],
offset: 'bottom-in-view',
onBeforePageLoad: function () {
$('.loading').show();
},
onAfterPageLoad: function () {
$('.loading').hide();
$(document).ready(function(){
function updateText(btn, newCount, verb){
btn.text(newCount + " " + verb)
}
$(".follow-btn").click(function(e){
e.preventDefault()
var this_ = $(this)
var badge = this_.find('.unlike-update')
var followUrl = this_.attr("data-href")
var followCount = parseInt(this_.attr("data-follows")) | 0
var addFollow = followCount + 1
var removeFollow = followCount - 1
if (followUrl){
$.ajax({
url: followUrl,
method: "GET",
data: {},
success: function(data){
console.log(data)
var newFollows;
if (data.followed){
// updateText(this_, addLike, "Unlike")
// updateText(this_, data.likescount, badge)
updateText(this_, data.followscount, "Unfollow")
} else {
// updateText(this_, removeLike, "Like")
updateText(this_, data.followscount, "Follow")
// remove one like
}
}, error: function(error){
console.log(error)
console.log("error")
}
})
}
})
})
}})
</script>
{% include 'group/snippets/group_follow.html' %}
{% endblock %}
class GroupListView(LoginRequiredMixin, ListView):
model = Group
paginate_by = 5
context_object_name = 'groups'
template_name = 'group/group_list.html'
ordering = ['-date_created']

Can I render Django template's format with if else condition using javascript?

I am using creating a Django application where I want to list down different products in the Django template by JS AJAX way. I just wonder how I can render it through js -
So I have two function one is for create the template for each product and here if you notice I have if else condition-
function createTemplate(product) {
return `<div class="col-12 col-lg-3 col-md-6 col-sm-6 mb-45 hot sale">
<div class="single-product">
<div class="single-product__image">
<a class="image-wrap" href="{{product.get_absolute_url}">
<img src="{% if product.image %}
{{ product.image.url }}
{% else %}
{% static 'img/no_image.png' %}
{% endif %}" class="img-fluid" alt="">
</a>
<div class="single-product__floating-icons">
<span class="wishlist">
{% if product.id in wishlist_item_check %}
<a href="javascript:void(0)" id="wishlistalready_${product.id}" data-tippy="Already Exists"
data-tippy-inertia="true" data-tippy-animation="shift-away" data-tippy-delay="50"
data-tippy-arrow="true" data-tippy-theme="sharpborder" data-tippy-placement="left"><i
class="ion-android-favorite" style="color:red"></i></a>
{% endif %}
</span>
</div>
</div>
</div>
</div>`;
}
And another function to render all the products in a div with specific id (for example her id="products>"
function renderProducts(products) {
const template =
products.length === 0
? `
<p>No matching results found.</p>
`
: products.map((product) => createTemplate(product)).join('\n');
$('#products').html(template);
}
Lastly I am rendering all the products in a div
<div class="row" id="products">
Do let me know if we any better and easy way of doing the same.

Using Django Models to assign HTML div through jQuery

for the last few days I've been trying to create a method in jquery using django models and I have found myself to be very out of my depth and would appreciate and explanation I can get. So currently I have a django model that has the following information : name, date, location, semester. I use the first 3 pieces of information in displaying my html, however, I want to use 'semester' to see what div tag my items go into.
The semester tag can either return 'Fall' or 'Spring' values is there a way I can use this to assign the components to the correct div. So if semester is Fall then it should go into the div with the id 'fall-races' and if its spring it should go to 'spring-races'
Currently I only have a jquery working where I get all the elements and assign it to the other div.
Thank you for your help and any possible advice.
<div class="flex-column">
<div class="header shadow-lg">
<h1 class="text-center py-3">
Fall Schedule
</h1>
</div>
<div id="fall-races">
{% for race in race %}
<div class="regatta-card my-2 mx-2 ">
<h2 class="center-text py-2">{{ race.date }}</h2>
<h1 class="text-center my-2">{{ race.name }}</h1>
<h3 class="text-center mb-3">{{ race.location}}</h3>
<h6 class="text-center">Recap</h6>
</div>
{% endfor %}
</div>
<input type="button" onclick="findChildren()" value="Click it" />
<div class="header shadow-lg">
<h1 class="text-center py-3">
Spring Schedule
</h1>
</div>
<div id="spring-races">
</div>
</div>
<script>
function findChildren() {
var objChl = document.getElementById('fall-races').children;
var msg = document.getElementById('spring-races');
msg.innerHTML = '';
for (i = 0; i < objChl.length ; i++) {
msg.appendChild(objChl[i]);
}
}
</script>
Maybe you want something like this:
Html:
<!-- Some html stuff -->
<div id="fall-races">
{% for race in race %}
<div class="regatta-card my-2 mx-2 ">
<h2 class="center-text py-2">{{ race.date }}</h2>
<h1 class="text-center my-2">{{ race.name }}</h1>
<h3 class="text-center mb-3">{{ race.location}}</h3>
<h6 class="text-center">Recap</h6>
<input type="hidden" value="{{race.semester}}" />
</div>
{% endfor %}
</div>
<!-- Some html stuff -->
JS:
<script>
function findChildren() {
var parent = document.getElementById('fall-races');
var objChl = parent.children;
var msg = document.getElementById('spring-races');
msg.innerHTML = '';
for (i = 0; i < objChl.length ; i++) {
const element = objChl[i];
var value = element.getElementsByTagName("input")[0].value;
if (value==="Spring"){
msg.appendChild(element);
parent.removeChild(element);
}
}
}
</script>
This is like the simplest way to achieve that, hope it helps you.

Loop JavaScript in Ajax

i'm following the Django code that dynamically generates cards according to my amount of variables i have in a bank. For each card it consumes data from an API through ajax code. However, my ajax code is not being called every loop. It is called only once. What I can do is wrong, because I need ajax to be called every loop of HTML.
{% block content %}
<div id="auto" class="row">
{% for row in list %}
{% if row.state == 1 %}
<div class="col-xs-6 col-md-4">
<div class="card">
<h5 class="card-header">{{row.description}} - Temperatura Atual (˚C)</h5>
<!--<img class="card-img-top" src="{% static 'img/gauge.png' %}" width="100" height="200" alt="Card image cap">!-->
<canvas id="myChart-{{ forloop.counter }}" class="piechart"></canvas>
<script>
var rowId = {{ row.id }}
console.log(rowId);
readTempDinamic(rowId);
//refresh();
</script>
<p class="text-center font-weight-bold" style="font-size: 0.7rem"><span id="datetime"></span></p>
Show
</div>
</div>
{% endif %}
{% endfor %}
</div>
{% endblock content %}
function readTempDinamic(rowId) {
var endpointTemp = '/api/weatherData/getSensor/1/' + rowId + '/'
console.log(endpointTemp);
/* ############################################################################# */
$.ajax({
method: "GET",
url: endpointTemp,
success: function(data){
var row = []
var value = []
var read_data = []
row = data.row
value = data.value
read_data = data.read_date
generateGaugeCharts(row[0], read_data[0], value[0])
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
/* ############################################################################# */
}

jquery use diferente variables in the same <p> from fields from database

http://prntscr.com/ir16ez
I have a problem, i cannot put diferent amounts in my shopping cart because when i choose a quantity, the program take what i choose and does the result for money etc,(working fine here) and brings the quantity to the shopping cart named "encomenda" but when i add a diferent item, the quantity changes to all instead of changing to only one, ssry from my english
//shopping cart html
<div class="rightdiv">carrinho
<div id="encomenda" class="expandContent">
<h3 class="header">
<div class="headerColumn1">Encomenda</div>
<div class="headerColumn2 expand"><img src="img/plus.png"/></div>
<div class="expandedContentClearFloat"></div>
</h3>
<div class="expandedContent">
{% for item in data %}
<div class="product-removal">
<article class="product">
<header>
<img src="{{ item.img|e }}" class="iconcomp">
</header>
<div class="content">
<h1>{{ item.marca|e }}</h1>
{{ item.descr|e }}
</div>
<footer class="content">
<h2 class="full-price fixed fixed-encomenda">
{{ item.preco_unit|e }}€
</h2>
<p class='quantidade' ></p> **//shows the amount here**
<a class='pull-right adicionar adicionar-encomenda' data-id='{{ item.id|e }}'
data-preco='{{ item.preco_unit|e }}' data-modelo="{{ item.modelo|e }}" data-marca="{{ item.marca|e }}" data-descr="{{ item.descr|e }}">
<h2 class="full-price">
{{ item.preco_unit|e }}€
</h2>
</a>
<h2 class="price">
{{ item.preco_unit|e }}
</h2>
</footer>
</article>
</div>
{% endfor %}
<h1 id='valor_configuracao' class='pull-right' value='data-preco'>0</h1>
</div>
<input type="button" id="enviar" value="enviar" data-mensagem="ola">
</div>
</div>
//add disco for example
$('.adicionar-disco').click(function () {
id = $(this).data('id');
var allExceptClicked = $('.adicionar-disco').not(this);
AdicionarItem(allExceptClicked, "disco", "disco2");
$(this).data('quantidade', parseFloat($(this).parent().find("span.qt").text()));
$(this).parent().parent().find("button.close-disco").data('quantidade', parseFloat($(this).parent().find("span.qt").text()));
preco = preco + ($(this).data("preco")* $(this).data('quantidade'));
p=$(this).data('quantidade'); **//receive in p the amount**
var rounded = Math.round((preco) * 100) / 100;
$('#valor_configuracao').html(rounded);
$('.adicionar-encomenda').each(function () {
var productRow = $(this).parent().parent();
var i = $(this).data('id');
if (i == id) {
productRow.show();
alert(p);
$(".quantidade").text(p);**//give the <p> variable that is in the "encomenda" p that has the amount needed**
//$("p").attr(".quantidade",p);
//Marcar item como selecionado
$(this).attr("data-selecionado","sim");
}
});
});
the statement $(".quantidade").text(p) set the same value at all element with class="quantitade", and all item of your chart have class="quantitade".
You should uniquely identify the div where you want to set the value, with id attribute, if possible, generated with the product id.

Categories