What to do when looping repeats in 2 different areas - javascript

The code gets the values of the input and sends it to the textarea, but when you add more than one title the values are repeated in the result of the titles, for example, the DESCRIPTIONS of title 1 are the same as in title 2, why does this happen? and how to make it work without changing the purpose?
Run the code in codepen.io or jsfiddle.net
This is what happens:
This is what should happen:
function result() {
var inp2 = document.getElementsByName("inp2");
var titu = document.getElementsByName("titu");
var res = document.getElementById("result");
res.value = "";
if (titu[0]) {
for (var k = 0; k < titu.length; k++) {
if (titu[k].value.trim() != '') {
res.value += `<div>
<span>${titu[k].value.trim()}</span>
</div>
<ul>\n`;
for (var j = 0; j < inp2.length; j++) {
if (inp2[j].value.trim() != '') {
res.value += `<li>${inp2[j].value.trim()}</li>\n`;
}
}
}
}
}else {
console.log("test")
res.value += `<ul>\n`;
for (var l = 0; l < inp2.length; l++) {
if (inp2[l].value.trim() != '') {
res.value += `<li>${inp2[l].value.trim()}</li>\n`;
}
}
}
};
// -----------------------------------------
if (document.getElementById("add2")) {
let cont2 = 1;
document.getElementById("add2").onclick = function clone2() {
let container2 = document.getElementById("output2");
let tempLinha2 = document.querySelector('#template2');
let clone2 = document.importNode(tempLinha2.content, true);
const label2 = clone2.querySelector("label");
label2.htmlFor = cont2;
clone2.querySelector("input").className = cont2;
container2.appendChild(clone2);
cont2++;
};
document.getElementById("del2").onclick = function del2() {
document.querySelector('#output2 #linha2:last-child').remove();
};
}
// ---------------------------------------
if (document.getElementById("addtit")) {
let cont3 = 1;
document.getElementById("addtit").onclick = function clone3() {
let container3 = document.getElementById("output2");
let tempLinha3 = document.querySelector('#template3');
let clone3 = document.importNode(tempLinha3.content, true);
const label3 = clone3.querySelector("label");
label3.htmlFor = cont3;
clone3.querySelector("input").className = cont3;
container3.appendChild(clone3);
cont3++;
document.getElementById('add2').id = 'add3';
document.getElementById('del2').id = 'del3';
};
document.getElementById("deltit").onclick = function deltit() {
document.querySelector('#output2 #alg:last-child').remove();
document.getElementById('add3').id = 'add2';
document.getElementById('del3').id = 'del2';
};
}
// -----------------------------------------
if (document.getElementById("add3")) {
let cont4 = 1;
document.getElementById("add3").onclick = function clone4() {
let container4 = document.getElementById("output3");
let tempLinha4 = document.querySelector('#template2');
let clone4 = document.importNode(tempLinha4.content, true);
const label4 = clone4.querySelector("label");
label4.htmlFor = cont4;
clone4.querySelector("input").className = cont4;
container4.appendChild(clone4);
cont4++;
};
document.getElementById("del3").onclick = function del4() {
document.querySelector('#output3 #linha2:last-child').remove();
};
}
<div class="container">
<button id="addtit">+ TITLE</button>
<button id="deltit">- TITLE</button>
<button id="add2">+ DESCRIPTION</button>
<button id="del2">- DESCRIPTION</button>
<div id="output2"></div>
<div class='botoes'>
<button onclick="result()" id='done'>DONE</button>
</div>
<div class="header"><span class="title">RESULT</span>
</div>
<div class="linha"><textarea id="result"></textarea>
</div>
</div>
<!-- template 2 -->
<template id="template2">
<div class="linha" id="linha2"><div class="coluna1"><label for="0">DESCRIPTION:</label></div><div class="coluna2"><input name="inp2" class="0" type="text"/></div>
</div>
</template>
<!-- template 3 -->
<template id="template3">
<div id="alg">
<div class="linha"><div class="coluna1"><label for="0">TITLE:</label></div><div class="coluna2"><input name="titu" class="0" type="text"/></div>
</div>
<div class="linha" id="linha3"><div class="coluna1"><label for="0">DESCRIPTION:</label></div><div class="coluna2"><input name="inp2" class="0" type="text"/></div>
</div>
<div id="output3"></div>
</div>
</template>

Ok. it's because this part of code in function result:
if (titu[0]) {
for (var k = 0; k < titu.length; k++) {
if (titu[k].value.trim() != '') {
res.value += `<div>
<span>${titu[k].value.trim()}</span>
</div>
<ul>\n`;
for (var j = 0; j < inp2.length; j++) {
if (inp2[j].value.trim() != '') {
res.value += `<li>${inp2[j].value.trim()}</li>\n`;
}
}
}
}
}
your titles have the same names : 'titu' , and your descriptions have same names : 'inp2', and you have two nested loops, for each title, loop on description, and it results as you see.
it's better to change your code and make different names and ids
by the way. if you persist to do not change your code, you should use one loop for both of them, like this code
if (titu[0]) {
for (var k = 0; k < titu.length; k++) {
if (titu[k].value.trim() != '') {
res.value += `<div>
<span>${titu[k].value.trim()}</span>
</div>
<ul>\n`;
if (inp2[k].value.trim() != '') {
res.value += `<li>${inp2[k].value.trim()}</li>\n`;
}
}
}
}
UPDATE
for the case of more description for each title, you have to change the code of onClick methods of Title+ and Description+, the added title and all of its description must have same parent, and after doing that, it's possible to solve the problem like this . (assuming the parent that I already have said has class name 'parent')
function result() {
var parents = document.querySelectorAll(".parent")
parents.forEach(function(parent){
var title = parent.querySelector("titu");
var descriptions = parent.querySelectorAll("inp2");
var res = document.getElementById("result");
if (title.value.trim() != '') {
res.value += `<div>
<span>${title.value.trim()}</span>
</div>
<ul>\n`;
}
descriptions.forEach(function(inp2){
if (inp2.value.trim() != '') {
res.value += `<li>${inp2.value.trim()}</li>\n`;
}
});
});
}
notice that this code could work after modifying Title+ and Description+ events and add same parent with class name parent to title and descriptions inputs

Related

Is there anyway I can check for duplicate in localStorage

I am creating a shopping cart with products fetch from a fake json-server. Each time I click the "add to cart" button, I want the product to be push into an array, and if it does exist in the array, I want to increase it by 1
const productGrid = document.querySelector('.grid__product');
const addToCartBtn = document.getElementsByClassName('add-to-cart-btn');
const tableBody = document.querySelector('.table__body');
eventListeners();
//all event listeners
function eventListeners() {
window.addEventListener('DOMContentLoaded', () => {
loadJSON();
loadCart();
})
productGrid.addEventListener('click', purchaseProduct)
}
//load json file into grid display
function loadJSON() {
fetch('http://localhost:3000/products').then(response => {
response.json().then(data => {
let html = '';
data.forEach(product => {
html += `<div class="legacy__items__detail" id='product-${product.id}'><img class='product__img' src="${product.img}" alt="OHUI">
<div class="legacy__items__detail__content legacy-content">
<h4 class='product__name'>${product.productName}</h4><a href="">
<p class='product__category'>${product.name}</p></a><span class="price">${product.price}<small>vnd</small></span>
</div>
<div class="legacy__items__detail__icon">
<div class="legacy-cta">
<button class='add-to-cart-btn'>Mua hàng</button>
<i class="fas fa-heart"></i><i class="fas fa-sync-alt"></i>
</div>
</div>
</div>`;
})
productGrid.innerHTML = html;
})
})}
function purchaseProduct(e) {
if (e.target.classList.contains('add-to-cart-btn')) {
let product = e.target.parentElement.parentElement.parentElement;
getProductInfo(product);
}
}
//get product info after add-cart btn is clicked
function getProductInfo(product) {
let productInfo = {
name: product.querySelector('.product__name').textContent,
imgSrc: product.querySelector('.product__img').src,
category: product.querySelector('.product__category').textContent,
price: parseInt(product.querySelector('.price').textContent),
count: 1,
}
saveProductInStorage(productInfo);
}
function saveProductInStorage(item) {
let products = []
localStorage.setItem('products', JSON.stringify(products));
if(products.indexOf(item) === -1) {
products.push(item)
} else {
item.count++;
}
console.log(products)
}
I have tried several method but the more I try, the more I getting stuck. Can someone please help me with this ?
Edit :
I have succeed in pushing the item in the array and when there is duplicate,the quantity of the item increase, however, I wanna set the products array in the localStorage. Any help is appreciated!
if (products.length === 0) {
products.push(item);
console.log(products);
return;
}
for (let i = 0; i < products.length; i++) {
if (products[i].name === item.name) {
products[i].count++;
console.log(products);
return;
}
}
products.push(item);
}
Slight change to the above answer:
var myContent = document.getElementById("myTextarea").value;
var savedProducts = JSON.parse(localStorage.getItem("products")) || [];
for (var i = 0; i < savedProducts.length; i++) {
if (JSON.parse(myContent).name === savedProducts[i].name) {
savedProducts[i].count++;
alert(`Found Duplicate. Not inserting again ${myContent}`)
} else if (i == savedProducts.length - 1) {
alert(`Inserted ${myContent}`)
savedProducts.push(JSON.parse(myContent));
localStorage.setItem("names", JSON.stringify(savedProducts))
return;
}
}
Tested and seems to be working.
Here is a fully functional code:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1>Product Retrieve from Locastorage demo</h1>
<textarea id="myTextarea" rows="10" cols="80"></textarea>
<p></p>
<button onclick="saveToCart()">Save to Cart</button>
<button onclick="loadCart()">Load from Cart</button>
<p id="myCart"></p>
<script>
var products = [];
localStorage.setItem("products", JSON.stringify(products))
function saveToCart() {
var productInfo = document.getElementById("myTextarea").value;
var savedProducts = JSON.parse(localStorage.getItem("products")) || [];
if (products.length === 0) {
products.push(JSON.parse(productInfo));
localStorage.setItem("products", JSON.stringify(products))
//console.log(savedProducts.length)
} else {
for (var i = 0; i <= savedProducts.length; i++) {
if (JSON.parse(productInfo).name === savedProducts[i].name) {
savedProducts[i].count++;
//alert(`Found Duplicate at position ${i}. Not inserting again ${productInfo}`)
alert(`${JSON.parse(productInfo).name} already exists`)
} else if (i == savedProducts.length - 1) {
alert(`Inserted ${productInfo} at position ${i}`)
savedProducts.push(JSON.parse(productInfo));
localStorage.setItem("products", JSON.stringify(savedProducts))
console.log(savedProducts.length)
return;
}
}
}
}
function loadCart() {
var products = localStorage.getItem("products");
products = JSON.parse(products)
var col = [];
for (var i = 0; i < products.length; i++) {
for (var key in products[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
///creating a table to load data-- start
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < products.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = products[i][col[j]];
}
}
var finalOutput = document.getElementById("myCart");
finalOutput.innerHTML = "";
finalOutput.appendChild(table);
///creating a table to load data-- end
}
</script>
</body>
</html>
I may be misunderstanding the question but if you have all of their purchased products in local storage couldn't you use JSON.parse(localStorage.getItem("products") to get all the products then use a for loop to check if the item being purchased already exists
savedProducts = JSON.parse(localStorage.getItem("products"));
for(var i = 0; i < savedProducts.length; i++){
if(item.name == savedProducts[i].name){
savedProducts[i].count++;
}else if(i == savedProducts.length-1){
savedProducts.push(item);
}
}
localStorage.setItem("products", JSON.stringify(savedProducts));
I haven't tested that but there's an example

HTML Div Element turns to null when I'm accessing it a 2nd time?

Here are the relevant bits of the client-side code:
function simpsonsShow(forest) {
alert(document.getElementById("simpsons"));
var ind = simpsonsIndex(forest).toFixed(2); // simpsonsIndex is a function not shown here
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML =
document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function () {
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function () {
forest = forestGenerate(content);
simpsonsShow(forest);
});
document.getElementById("sim").appendChild(button);
});
});
When that simpsonsShow function is ran a second time, all of a sudden document.getElementById("simpsons") becomes null even though upon first try, it's a proper HTML Div Element.
Here are the relevant parts of the HTML:
<head>
<script src="sim.js"></script>
</head>
<body>
<div id="content">
<div id="intro">
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
</div><!--close id="content"-->
</body>
</html>
I've added the code snippet: The website works by pressing generate, then continually pressing generate. The error pops up once you press generate a 2nd time
function forestGenerate(content) {
const forest = [];
if (content.length === 0) {
const possible = ["", "🌲", "🌳", "🌴", "🌵", "🌶", "🌷", "🌸", "🌹", "🌺", "🌻", "🌼", "🌽", "🌾", "🌿", "🍀", "🍁", "🍂", "🍃"];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
else {
const possible = [...content, ""];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
for (let i = 0; i < forest.length; i++) {
let row = document.createElement("div");
let newContent = document.createTextNode(forest[i]);
row.appendChild(newContent);
row.addEventListener("click", function () {
row.style.backgroundColor = "grey";
row.setAttribute("pinned", "yes");
});
document.getElementById("sim").appendChild(row);
}
return forest;
}
function simpsonsShow(forest) {
const simpsonsIndex = forest =>
1 - Object.entries(
[...forest.join("")].reduce(
(counts, emoji) => ({ ...counts, [emoji]: (counts[emoji] || 0) + 1 }),
{}
)
).reduce(([top, bottom], [species, count]) => [top + (count * (count - 1)), bottom + count], [0, 0])
.reduce((sumLilN, bigN) => sumLilN / (bigN * (bigN - 1)))
alert(document.getElementById("simpsons"));
var ind = simpsonsIndex(forest).toFixed(2);
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML = document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function () {
let element = document.getElementById("sim");
element.classList.add("hidden");
let element1 = document.getElementById("pushtray");
element1.classList.add("hidden");
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
if (ind <= .7) {
let over = document.createElement("div");
let newContent = document.createTextNode("WARNING: Simpson's Index Dropped To" + simpsonsIndex);
over.appendChild(newContent);
document.getElementById("pushtray").appendChild(over);
document.getElementById("pushtray").style.zIndex = "100";
document.getElementById("pushtray").style.right = "50px";
document.getElementById("pushtray").style.position = "fixed";
document.getElementById("pushtray").style.display = "block";
}
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function () {
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 0; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
document.getElementById("sim").removeChild(button);
forest = forestGenerate(content);
simpsonsShow(forest);
document.getElementById("sim").appendChild(button);
});
document.getElementById("sim").appendChild(button);
});
});
<!doctype html>
<html>
<head>
<title>FOREST SIMULATOR</title>
<script src="sim.js"></script>
<link rel="stylesheet" href="base.css" type="text/css" media="screen" title="no title" charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Lato|Playfair+Display" rel="stylesheet" >
</head>
<link href="https://fonts.googleapis.com/css?family=Lato|Playfair+Display" rel="stylesheet">
<body>
<div id="content">
<h1>FOREST SIMULATOR</h1>
<style>
.hidden{
display:none;
}
</style>
<div id="intro">
starting forest (leave empty to randomize):
<br />
<textarea id="inputForest" name="inputForest" cols="16" rows="8"></textarea>
<br />
<button>generate</button>
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
<div id="pushtray" class="overlay">
</div>
</div><!--close id="content"-->
</body>
</html>
#simpsons is a child of #sim. The problem is in this code here:
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 0; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
It effectively removes all div children of #sim which don't have a pinned attribute. Try removing only divs after the first index, thereby keeping #simpsons (which is the first div inside #sim):
for (let i = 1; i < curr.length; i++) {
function forestGenerate(content) {
const forest = [];
if (content.length === 0) {
const possible = ["", "🌲", "🌳", "🌴", "🌵", "🌶", "🌷", "🌸", "🌹", "🌺", "🌻", "🌼", "🌽", "🌾", "🌿", "🍀", "🍁", "🍂", "🍃"];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
} else {
const possible = [...content, ""];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
for (let i = 0; i < forest.length; i++) {
let row = document.createElement("div");
let newContent = document.createTextNode(forest[i]);
row.appendChild(newContent);
row.addEventListener("click", function() {
row.style.backgroundColor = "grey";
row.setAttribute("pinned", "yes");
});
document.getElementById("sim").appendChild(row);
}
return forest;
}
function simpsonsShow(forest) {
const simpsonsIndex = forest =>
1 - Object.entries(
[...forest.join("")].reduce(
(counts, emoji) => ({ ...counts,
[emoji]: (counts[emoji] || 0) + 1
}), {}
)
).reduce(([top, bottom], [species, count]) => [top + (count * (count - 1)), bottom + count], [0, 0])
.reduce((sumLilN, bigN) => sumLilN / (bigN * (bigN - 1)))
var ind = simpsonsIndex(forest).toFixed(2);
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML = document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function() {
let element = document.getElementById("sim");
element.classList.add("hidden");
let element1 = document.getElementById("pushtray");
element1.classList.add("hidden");
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
if (ind <= .7) {
let over = document.createElement("div");
let newContent = document.createTextNode("WARNING: Simpson's Index Dropped To" + simpsonsIndex);
over.appendChild(newContent);
document.getElementById("pushtray").appendChild(over);
document.getElementById("pushtray").style.zIndex = "100";
document.getElementById("pushtray").style.right = "50px";
document.getElementById("pushtray").style.position = "fixed";
document.getElementById("pushtray").style.display = "block";
}
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function() {
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 1; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
document.getElementById("sim").removeChild(button);
forest = forestGenerate(content);
simpsonsShow(forest);
document.getElementById("sim").appendChild(button);
});
document.getElementById("sim").appendChild(button);
});
});
.hidden {
display: none;
}
<div id="content">
<h1>FOREST SIMULATOR</h1>
<div id="intro">
starting forest (leave empty to randomize):
<br />
<textarea id="inputForest" name="inputForest" cols="16" rows="8"></textarea>
<br />
<button>generate</button>
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
<div id="pushtray" class="overlay">
</div>
</div>

Removing Target _blank in JavaScript

I want to remove the target="_blank" in the given code and also, show me how to add unordered list or ordered list.
Random Post example: Check the bottom of the page
<div class='kotakleft'>
<div class='boxleft'>
<ul id='random-posts' />
<script>
var homePage = "http://www.example.com/",
numPosts = 7;
function randomPosts(a) {
if (document.getElementById("random-posts")) {
var e = shuffleArray(a.feed.entry), title, link, img, content = "", ct = document.getElementById("random-posts");
for (var i = 0; i < numPosts; i++) {
for (var j = 0; j < numPosts; j++) {
if (e[i].link[j].rel == "alternate") {
link = e[i].link[j].href;
break
}
}
var title = e[i].title.$t;
content += '<div class="random-posts"><li>' + title + '</li></div>'
}
ct.innerHTML = content
}
}
function shuffleArray(arr) {
var i = arr.length, j, temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp
}
return arr
}
var random_post = document.createElement('script');
random_post.src = homePage + '/feeds/posts/summary?alt=json-in-script&orderby=published&max-results=999&callback=randomPosts';
document.getElementsByTagName('head')[0].appendChild(random_post);
</script>
</div>
</div>
How can I do this?
It's very simple, you just need to change a few things:
<div class='boxleft'>
<ul id='random-posts' />
<script>
var homePage = "http://www.example.com/",
numPosts = 7;
function randomPosts(a) {
if (document.getElementById("random-posts")) {
var e = shuffleArray(a.feed.entry), title, link, img, content = "", ct = document.getElementById("random-posts");
content = '<ul>';
for (var i = 0; i < numPosts; i++) {
for (var j = 0; j < numPosts; j++) {
if (e[i].link[j].rel == "alternate") {
link = e[i].link[j].href;
break
}
}
var title = e[i].title.$t;
content += '<li><div class="random-posts">' + title + '</div></li>'
}
content = '</ul>';
ct.innerHTML = content
}
}
function shuffleArray(arr) {
var i = arr.length, j, temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp
}
return arr
}
var random_post = document.createElement('script');
random_post.src = homePage + '/feeds/posts/summary?alt=json-in-script&orderby=published&max-results=999&callback=randomPosts';
document.getElementsByTagName('head')[0].appendChild(random_post);
</script>
</div>
</div>

Morris Bar-chart(Error: <rect> attribute width: A negative value is not valid. ("-0.2634408602150538") in the first click im getting like this

> In the first click my chart is not displaying(but data is present),
after changing the date it is loading n displaying, from past 3 days
I'm trying to fix this issue but couldn't.
<div class="box box-success barchart">
<div ng-show="dataFound" class="box-body chart-responsive">
<div class="y-axis"><text ng-show="isBarShowing" id="y-axis" class="axis">Inverter Capacity kWh →</text></div>
<div class="chart" id="bar-chart">
</div>
</div>
<div id="x-axis" ng-show="isBarShowing"><text class="axis">Inverters →</text></div>
</div>
js file
function generateMultipleBarValues() {
var data = $scope.data;
var timeKeys = [];
var tempMap = [];
barData = [];
for (var i = 0; i < data.length; i++) {
var datum = data[i];
var timeKey = datum.TimeofReading.split(' ')[0];
if (timeKeys.indexOf(timeKey) == -1) {
timeKeys.push(timeKey);
}
}
for (var i = 0; i < timeKeys.length; i++) {
for (var j = 0; j < data.length; j++) {
var time = data[j].TimeofReading.split(' ')[0];
if (timeKeys[i] == time) {
if (typeof tempMap[time] == 'undefined') {
tempMap[time] = { date: time };
tempMap[time]['Inv ' + data[j].InverterId] = data[j].Readingby;
} else {
tempMap[time]['Inv ' + data[j].InverterId] = data[j].Readingby;
}
}
}
barData.push(tempMap[timeKeys[i]]);
}
if (barData.length == 0) {
$('#bar-chart').hide();
$scope.isBarShowing = false;
$scope.viewDisabled = true;
$scope.dataFound = false;
return;
} else {
$('#bar-chart').show();
timeKeys = [];
tempMap = [];
console.log(JSON.stringify(barData));
generateBarChart(barData);
barData = [];
$scope.dataFound = true;
$scope.isBarShowing = true;
$scope.viewDisabled = false;
$scope.dataFound = true;
}
}
// generate barchart
function generateBarChart(barData) {
var keyNames = Object.keys(barData[0]);
var keys = [];
for (var i = 1; i < keyNames.length; i++) {
keys.push('Inv ' + i);
for (var j = 0; j < barData.length; j++) {
barData[j][keys[i - 1]] = barData[j][keyNames[i]];
delete barData[j][keyNames[i]];
}
}
console.log(JSON.stringify(keys));
console.log(JSON.stringify(barData));
$('#bar-chart').empty();
bar = new Morris.Bar({
element: 'bar-chart',
data: barData,
xkey: 'date',
ykeys: keys,
labels: keys,
});
keys = [];
}
here each time when I'm changing the select range in facing the of
negative value, initially the width is less(when we are loading the
chart first time) but in the second time, it is loading correctly.
please some on help me to fix this issue... were my chart can be
display in all the time
Please put width for your div element. like width:auto or width:600px.
<div class="box box-success barchart">
<div ng-show="dataFound" class="box-body chart-responsive" style="width:auto; height:350px">
<div class="y-axis"><text ng-show="isBarShowing" id="y-axis" class="axis">Inverter Capacity kWh →</text></div>
<div class="chart" id="bar-chart">
</div>
</div>
<div id="x-axis" ng-show="isBarShowing"><text class="axis">Inverters →</text></div>
</div>

checking for duplicate file while uploading multiple file in Javascript

I used the below code to upload multiple files. Its working absolutely fine but as i need to check that the file which i am uploading is duplicate or not, i am facing one problem in that. I created one function called checkDuplicate for that and calling it inside the function. But the problem is that the for loop is looping double the size of the array. I don't know why it is so. Please kindly help me if anyone has any idea.
Here is the Javascript
<script type="text/javascript">
function MultiSelector(list_target, max) {
this.list_target = list_target;
this.count = 0;
this.id = 0;
if (max) {
this.max = max;
} else {
this.max = -1;
};
this.addElement = function(element) {
if (element.tagName == 'INPUT' && element.type == 'file') {
element.name = 'file_' + this.id++;
element.multi_selector = this;
element.onchange = function() {
var new_element = document.createElement('input');
new_element.type = 'file';
this.parentNode.insertBefore(new_element, this);
this.multi_selector.addElement(new_element);
this.multi_selector.addListRow(this);
this.style.position = 'absolute';
this.style.left = '-1000px';
};
if (this.max != -1 && this.count >= this.max) {
element.disabled = true;
}
;
this.count++;
this.current_element = element;
}
else {
alert('Error: not a file input element');
}
;
};
this.addListRow = function(element) {
var new_row = document.createElement('div');
var new_row_button = document.createElement('img');
new_row_button.setAttribute("src","<%=request.getContextPath()%>/images/deletei.gif");
new_row_button.onclick = function() {
this.parentNode.element.parentNode.removeChild(this.parentNode.element);
this.parentNode.parentNode.removeChild(this.parentNode);
this.parentNode.element.multi_selector.count--;
this.parentNode.element.multi_selector.current_element.disabled = false;
return false;
};
if(checkDuplicate(element)) {
new_row.element = element;
new_row.innerHTML = element.value + " ";
new_row.appendChild(new_row_button);
this.list_target.appendChild(new_row);
}
};
};
function checkDuplicate(element) {
var arr = new Array();
var i = 0,dup=0;
//alert(new_row.element = element.value);
if(dup==0) {
arr[i++] = element.value;
dup=1;
}
alert("Length ==> "+ arr.length);
for ( var j = 0; j < arr.length; j++) {
alert("Name ==> " + arr[j]);
if(arr[j] == element.value && j>=1) {
alert("Duplicate");
} else {
alert("Not Duplicate");
arr[i++] = element.value;
}
}
}
</script>
Here is the HTML
<body>
<!-- This is the form -->
<form enctype="multipart/form-data" action=""method="post">
<input id="my_file_element" type="file" name="file_1">
<input type="submit">
<br/>
<br/>
Files:
<!-- This is where the output will appear -->
<div id="files_list"></div>
</form>
<script>
var multi_selector = new MultiSelector(document
.getElementById('files_list'), 15);
multi_selector.addElement(document.getElementById('my_file_element'));
</script>
</body>
</html>
because you have the arr[i++] = element.value; in the last line, and j < arr.length in the for, so every time the array.lenght gets bigger and bigger.
change the for line to these two lines:
var len = arr.length;
for ( var j = 0; j < len; j++) {

Categories