I'm using flask for my application and I want a div to appear when the user presses on one of the selected buttons. While this works for every button, the "liking feature" only works for the div in the first button. There is an unfilled heart favicon that I swap for a filled in one when the user presses the heart. However, this only works for the first div and not the rest and I can't seem to know why.
function like(status) {
console.log("here");
if (status == 'True') {
console.log(status);
document.getElementById('nofill').style.display = "none";
document.getElementById('fill').style.display = "inline-block";
} else if (status == 'False') {
console.log(status);
document.getElementById('fill').style.display = "none";
document.getElementById('nofill').style.display = "inline-block";
}
}
function showInfo(tag, button_id) {
console.log("Got to the actions.js file");
console.log(button_id);
var selected_tag_div = document.getElementById(tag);
var button = document.getElementById(button_id);
if (selected_tag_div.style.display === "none") {
selected_tag_div.style.display = "block";
selected_tag_div.style.textAlign = "left";
// selected_tag_div.style.backgroundColor = "#5BC0DE";
button.style.opacity = .7;
selected_tag_div.style.height = "100px";
} else {
selected_tag_div.style.display = "none";
button.style.backgroundColor = "#5BC0DE";
button.style.opacity = 1;
}
}
{% if output %}
<p class="section-title">Top #'s to use</p>
<div class="output-container text-center">
{% for tag in output %} {% set button_id = tag[1:] + "-btn" %}
<button type="button" onclick="showInfo('{{tag[1:]}}', '{{button_id}}')" id={{button_id}} class="btn btn-info tag_buttons">{{tag}}
</button>
<div class="selected-container row" id={{tag[1:]}} style="display: none">
<div class="col-sm-12">
<div class="like-button">
<span style="float: right;" onclick="like('True')"><i id='nofill' class="far fa-heart" style="color: #000000; font-size:1.5em; display: inline-block"></i></span>
<span style="float: right;" onclick="like('False')"><i id='fill' class="fas fa-heart" style="color: #FF0000; font-size:1.5em;"></i></span>
</div>
</div>
</div>
{% endfor %}
</div>
{% endif %}
HTML tag id attribute must be unique so you are not supposed to have elements with the same id in the DOM.
<span style="float: right;" onclick="like('True')"><i id='nofill' class="far fa-heart" style="color: #000000; font-size:1.5em; display: inline-block"></i></span>
<span style="float: right;" onclick="like('False')"><i id='fill' class="fas fa-heart" style="color: #FF0000; font-size:1.5em;"></i></span>
One option is to use class attribute instead of id:
<span style="float: right;" onclick="like('True')"><i class='nofill' class="far fa-heart" style="color: #000000; font-size:1.5em; display: inline-block"></i></span>
<span style="float: right;" onclick="like('False')"><i class='fill' class="fas fa-heart" style="color: #FF0000; font-size:1.5em;"></i></span>
Also look at how to use this keyword and learn more about JS events.
Related
The app is Gpa calculator using node js with express.But there is problem,it works fine for single user but when any other user doing same in same time,then the marks are getting combined and showing wrong values.I want build app which works separately for each user without combining the values.
const express=require("express");
const https=require("https");
const bodyParser=require("body-parser");
const mongoose=require("mongoose");
const lr=require("livereload");
const app=express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine","ejs");
var list=[0];
var clist=[0];
var len=0;
var sum=0;
var csum=0;
var fin;
var per;
app.get("/",function(req,res){
res.render("index",{len:len});
});
app.post("/",function(req,res){
var cr=req.body.crd;
var sc=req.body.scr;
var ccr=parseInt(cr);
if(sc=="S"){
sc=10;
}
else if(sc=="A"){
sc=9;
}
else if(sc=="B"){
sc=8;
}
else if(sc=="C"){
sc=7;
}
else if(sc=="D"){
sc=6;
}
else{
sc=0;
len=parseInt(len)-1;
res.send("Give valid inputs.");
}
var tot=parseInt(cr)*parseInt(sc);
len=list.length;
clist.push(ccr);
list.push(tot);
res.redirect("/");
});
app.post("/calculate",function(req,res){
for(var i=0;i<list.length;i++){
sum+=list[i];
}
for(var j=0;j<clist.length;j++){
csum+=clist[j];
}
fin=sum / csum;
var finn=fin.toString();
var finnn=finn.slice(0,4);
per=fin*9.5;
var perr=per.toString();
var perrr=perr.slice(0,5);
res.render("display",{fin:finnn, per:perrr});
})
app.post("/reset",function(req,res){
list=[0];
clist=[0];
len=0;
sum=0;
csum=0;
res.redirect("/");
})
var ser=app.listen(process.env.PORT || 3000,function(){
console.log("server is running on port 3000");
});
<%- include("bootstrap") %>
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body style="background-color: #fffbdf;">
<nav style="margin-bottom: 2%;" class="navbar navbar-expand-lg navbar-light bg-dark">
<a style="color: white;" class="navbar-brand" href="#">Veltech Calculator</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
</div>
</div>
</nav>
<center>
<form action="/" method="post">
<label><h6>Enter Credits :</h6></label>
<input id="crd" placeholder="Enter credits" style="margin: 2%" type="text" name="crd" required autofocus>
<label><h6>Enter Grade : </h6></label>
<input id="scr" placeholder="Enter grade in CAPITAL" style="margin: 2%" type="text" name="scr" required="Fill this" autofocus><br>
<% if(len==0){%>
<h5 style="color: red; margin-bottom: 2%;">No subject is added</h5>
<% } else{ %>
<h5 style="color: green; margin-bottom: 2%;"><%= len %> subjects are are added</h5>
<% } %>
<button type="submit" id="add" class="btn btn-warning" style="width: 80px;">ADD</button><br>
<div style="margin-bottom: 0.5%; margin-top: 2%; display:inline-block;" class="alert alert-danger" role="alert">
<b>NOTE</b>: If you done anything wrong while adding subjects,try to click on RESET button.Else may get wrong values.
</div>
</form>
<form action="/calculate" method="post">
<button type="submit" id="cal" class="btn btn-primary btn-lg" style="margin-top: 3%; width: 200px;">Calculate</button>
</form>
<form action="/reset" method="post">
<button type="submit" id="reset" class="btn btn-secondary btn-lg" style="margin-top: 1%; width: 200px;">RESET</button>
</center>
<center>
<div style="background-color: #4ca1a3; margin-top: 2%" id="cf">
<h5 id="cfh" style="padding-top: 1%; color: #0c4271">Veltech Calculator</h5>
<label><b>Website links :</b></label>
<a style="padding-bottom: 1%; color: black;" href="https://www.veltech.edu.in">Veltech official site</a>
<h6 style="padding-bottom: 1%;"> #VeltechCalculator copy rights reserved/leela sairam</h6>
</div>
</center>
</body>
</html>
<%- include("bootstrap") %>
Store your user-specific data in a session instead of in global variables.
A session works by generating a unique ID for each visitor and storing it in a cookie. It has a central data store (which could just be an in-memory object or could be a file or database) which associates whatever data you like with that unique ID. When you want to read or write to it, you just get the ID from the cookie and look up the data based on it.
The express-session module will do all the heavy lifting for you.
I am trying to trigger a function through a event listener with only one click.
But it occurs after two click (in the first time) if I don't do F5 its trigger after one click.
Code:
HTML
<div class="main-header-navbar">
....
<span class="main-header-navbar-right-icons">
<i class="fas fa-search header-icon"></i>
<i class="fas fa-plus header-icon"></i>
</span>
</div>
JS
const ADD_FORM_BUTTON = document.querySelector(".fa-plus");
ADD_FORM_BUTTON.addEventListener("click", function (event) {
event.preventDefault();
if (ADD_FORM.style.display === "none") {
ADD_FORM.style.display = "flex";
} else ADD_FORM.style.display = "none";
});
What am I missing?
You probably need to add style="display: none;" to your ADD_FORM so that it's initially hidden, then when you click on the fa-plus it will display it. See the snippet below:
const ADD_FORM_BUTTON = document.querySelector(".fa-plus");
const ADD_FORM = document.getElementById("form");
ADD_FORM_BUTTON.addEventListener("click", function(event) {
event.preventDefault();
if (ADD_FORM.style.display === "none") {
ADD_FORM.style.display = "flex";
} else {
ADD_FORM.style.display = "none"
};
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<div class="main-header-navbar">
<span class="main-header-navbar-right-icons">
<i class="fas fa-search header-icon"></i>
<i class="fas fa-plus header-icon"></i>
</span>
<div id="form" style="display: none;">ADD_FORM</div>
</div>
I've got this button in which I'd like to insert an icon with JavaScript:
<button id="chat5" onclick="actualizarIdChat('{{ elemento.pk }}')" class="btn btn-secondary" style="background-color: maroon; border-color: transparent;border-radius: 15px;height: 60px;margin: 10px 0px 10px 0px;width: 90%;" type="button">
<img class="border rounded-circle" style="width: 50px;height: 50px;border-color: transparent;" src="{{ elemento.producto.info_producto.contenido_multimedia.0.contenido_url }}">
{{ elemento.producto.info_producto.nombre }}
</button>
This is the code I've defined to make it work, but it does nothing.
var idChat = 'chat5';
var icon = document.createElement("div");
icon.innerHTML = '<i class="fa fa-envelope"></i>';
document.getElementById(idChat).appendChild(icon);
How could I do it?
Update javascript part, it looks like:
var buttonElement = document.getElementById("chat5");
buttonElement.innerHTML = buttonElement.innerHTML + '<i class="fa fa-envelope"></i>';
It will work
I'm having a list of users where the admin can approve/decline.For these two action i'm using show/hide oncllick the code works.But in multiple rows for any action button onclick it shows/hide the content.I want paticular row's action button 'ld show/hide the content,on click of that button.How can I solve this?
Here is My view code laravel blade,
<script>
function showhide() {
var div = document.getElementById("collapse1");
if (div.style.display !== "none")
div.style.display = "none";
else
div.style.display = "block";
}
</script>
Content:
<div>
<button href="#collapse1" class="btn btn-success nav-toggle" onclick="showhide()">Action</button>
</div>
#if($user->approved == 0)
<div id="collapse1" style="display:none">
<span>
<a href="{!! route('approve', ['id' => $user->id]) !!}"><img alt="" src="http://www.clker.com/cliparts/l/n/a/E/b/t/check-mark-button-hi.png"
style="height: 48px; width: 48px" /></a>
</span><br/>
#else
<span>
<a href="{!! route('decline', ['id' => $user->id]) !!}">
<img alt="" src="https://images.onlinelabels.com/images/clip-art/TzeenieWheenie/TzeenieWheenie_red_green_OK_not_OK_Icons_1.png"
style="height: 48px; width: 48px"/>
</a>
</span>
</div>
#endif
Script
#pushonce('custom-scripts')
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
#endpushonce
It conflict id
You need change id:
id="collapse1" => id="collapse{$user->id}"
js and html function like https://jsfiddle.net/ft9xprnb/3/ .You can see result by click link and content function edited: elem.getAttribute("href")
function showhide(elem)
{
console.log(elem.getAttribute("href"));
var div = document.getElementById(elem.getAttribute("href").replace("#", ""));
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
}
You can pass this in html
<button href="#collapse1" class="btn btn-success nav-toggle" onclick="showhide(this)">Action</button>
And then in JS
function showhide(elem)
{
var div = document.getElementById(elem.href.replace("#", ""));
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
}
This way the elem you will be passing to click will be the clicked element.
Try changing content to this
<div>
<button href="#collapse1" class="btn btn-success nav-toggle" onclick="showhide()">Action</button>
</div>
<div id="collapse1" style="display:none">
#if($user->approved == 0)
<span>
<a href="{!! route('approve', ['id' => $user->id]) !!}">
<img alt="" src="http://www.clker.com/cliparts/l/n/a/E/b/t/check-mark-button-hi.png" style="height: 48px; width: 48px"/>
</a>
</span>
<br/>
#else
<span>
<a href="{!! route('decline', ['id' => $user->id]) !!}">
<img alt="" src="https://images.onlinelabels.com/images/clip-art/TzeenieWheenie/TzeenieWheenie_red_green_OK_not_OK_Icons_1.png" style="height: 48px; width: 48px"/>
</a>
</span>
#endif
</div>
There is a table which displays files (one tr one file) there is a dropzonejs created on table so I can drag file and drop on table. I would like to add a "preview" as TR element of a table but I can't do this. This is how my preview template looks like:
<tr class="dz-preview">
<td><span class="name" data-dz-name></span></td>
<td><span class="size" data-dz-size></span></td>
<td colspan="5">
<div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress> </div>
</div>
</td>
</tr>
Problem is that Dropzone.js does this:
Dropzone.createElement = function(string) {
var div;
div = document.createElement("div");
div.innerHTML = string;
return div.childNodes[0];
};
TR or TBODY is not valid child of DIV so it will be created as TEXT, TEXT doesn't have property querySelectorAll, and there is an error.
Is there a solution to use TR or TBODY as preview template?
Just redefine Dropzone.createElement function in your code.
In my case I use jQuery:
$(function() {
Dropzone.createElement = function(string) {
var el = $(string);
return el[0];
};
var dropzone = new Dropzone(document.body, options);
});
So here's a little fix in Dropzone.createElement function that fixes the problem:
Replace this:
div = document.createElement("div");
With this:
if (string.substr(0, 3) == '<tr'){
// Table elements can not be wrapped into a div
div = document.createElement("tbody");
} else {
div = document.createElement("div");
}
While I recommend #strikes answer as the most suitable answer. I'm attaching this code of a complete implementation using a tabular format which is a extension of #strikes answer and DropzoneJS bootstrap template
PS: Run snippet is functional, so you can try running the snippet here to see if it is properly working.
$('#allselect').change(function () {
var selections = document.getElementsByName('selection');
for( var i=0; i<selections.length; i++){
if(selections[i].checked == false) {
selections[i].checked = true;
}
else {
if(selections[i].checked == true) {
selections[i].checked = false;
}
}
};
});
</script>
<script>
// Get the template HTML and remove it from the doument
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
Dropzone.createElement = function(string) {
var el = $(string);
return el[0];
};
var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
url: "{{ route('user.warehouse_images.store') }}", // Set the url
thumbnailWidth: 80,
paramName: "warehouse_image",
thumbnailHeight: 80,
parallelUploads: 20,
previewTemplate: previewTemplate,
autoQueue: false, // Make sure the files aren't queued until manually added
previewsContainer: "#previews", // Define the container to display the previews
clickable: ".fileinput-button", // Define the element that should be used as click trigger to select files.
renameFile: function(file) {
var dt = new Date();
var time = dt.getTime();
return time+file.name;
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
});
myDropzone.on("addedfile", function (file) {
// Hookup the start button
file.previewElement.querySelector(".start").onclick = function () {
myDropzone.enqueueFile(file);
};
});
// Update the total progress bar
myDropzone.on("totaluploadprogress", function (progress) {
document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
});
myDropzone.on("sending", function (file) {
// Show the total progress bar when upload starts
document.querySelector("#total-progress").style.opacity = "1";
// And disable the start button
file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});
// Hide the total progress bar when nothing's uploading anymore
myDropzone.on("queuecomplete", function (progress) {
document.querySelector("#total-progress").style.opacity = "0";
});
myDropzone.on("sending", function(file, xhr, formData){
formData.append("camera_id", "loremipsum");
console.log(file);
console.log(file.upload.filename);
console.log(xhr);
});
// Setup the buttons for all transfers
// The "add files" button doesn't need to be setup because the config
// `clickable` has already been specified.
document.querySelector("#actions .start").onclick = function () {
myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
};
document.querySelector("#actions .cancel").onclick = function () {
myDropzone.removeAllFiles(true);
};
html, body {
height: 100%;
}
#actions {
margin: 2em 0;
}
/* Mimic table appearance */
div.table {
display: table;
}
div.table .file-row {
display: table-row;
}
div.table .file-row > div {
display: table-cell;
vertical-align: top;
border-top: 1px solid #ddd;
padding: 8px;
}
div.table .file-row:nth-child(odd) {
background: #f9f9f9;
}
/* The total progress gets shown by event listeners */
#total-progress {
opacity: 0;
transition: opacity 0.3s linear;
}
/* Hide the progress bar when finished */
#previews .file-row.dz-success .progress {
opacity: 0;
transition: opacity 0.3s linear;
}
/* Hide the delete button initially */
#previews .file-row .delete {
display: none;
}
/* Hide the start and cancel buttons and show the delete button */
#previews .file-row.dz-success .start,
#previews .file-row.dz-success .cancel {
display: none;
}
#previews .file-row.dz-success .delete {
display: block;
}
.custom-control {
position: relative;
display: block;
min-height: 1.5rem;
padding-left: 2.5rem;
}
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/dropzone.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/basic.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/dropzone.js'></script>
</head>
<body>
<!--File Dropzone-- -->
<div id="actions" class="row">
<div class="col-lg-1">
<div class="custom-control custom-checkbox">
<input class="custom-control-input" type="checkbox" id="allselect">
<label for="allselect" class="custom-control-label"></label>
</div>
</div>
<div class="col-lg-7">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button dz-clickable">
<i class="fa fa-plus"></i>
<span>Add files...</span>
</span>
<button type="submit" class="btn btn-primary start">
<i class="fa fa-upload"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="fa fa-ban"></i>
<span>Cancel upload</span>
</button>
</div>
<div class="col-lg-4">
<!-- The global file processing state -->
<span class="fileupload-process">
<div id="total-progress" class="progress progress-striped active" role="progressbar" aria-valuemin="0"
aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress=""></div>
</div>
</span>
</div>
</div>
<div class="row">
<table class="table table-striped">
<thead>
<tr>
<th>Select</th>
<th>Image Preview</th>
<th>Image Name</th>
<th>Camera</th>
<th>Date</th>
<th>Progress</th>
<th>Actions</th>
</tr>
</thead>
<tbody class="table table-striped files" id="previews">
<tr id="template" class="file-row">
<td>
<input type="checkbox" name="selection">
</td>
<td>
<span class="preview"><img data-dz-thumbnail/></span>
</td>
<td>
<p class="name" data-dz-name></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</td>
<td>
<p class="cameraText"> Camera Not set</p>
</td>
<td>
<p class="timestamp">Date Not Set</p>
</td>
<td>
<p class="size" data-dz-size></p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0"
aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;"
data-dz-uploadprogress></div>
</div>
</td>
<td>
<button class="btn btn-primary start">
<i class="fa fa-upload"></i>
<span>Start</span>
</button>
<button data-dz-remove class="btn btn-warning cancel">
<i class="fa fa-ban"></i>
<span>Cancel</span>
</button>
<button data-dz-remove class="btn btn-danger delete">
<i class="fa fa-trash"></i>
<span>Delete</span>
</button>
</td>
<td>
<p class="camera" style="visibility: hidden"></p>
</td>
</tr>
</tbody>
</table>
</div>
</body>