Migrating to Bootstrap v4 caused a table to disappear - javascript

I wrote my code in Bootstrap v3, however, upon realising that it doesn't support Spinners and many of the CSS elements I've envisioned didn't have the style that I wanted, I want to switch to Bootstrap v4. I added all of the required scripts / css links to the head, however I noticed that one whole table from my code has frankly just disappeared. And I have no idea why. The table is on a separate html element, and works in Bootstrap v3 but not sure why it's not displaying with v4.
Code:
main2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<style>
</style>
</head>
<body>
<div id="header" style="background-color: white; width:100%; height:auto; position:fixed;">
<p id="statusText">Preparing supermarkets from Google Drive...</p>
<div id="form-group">
<input type="text" class="form-control" id="searchInput" placeholder="Search by Name or ID of Supermarket"/>
</div>
</div>
<!-- <div class="d-flex justify-content-center align-items-center" style="visibility:hidden;">
<div class="spinner-border" id="spinner" role="status">
</div> -->
</div>
<div class="container">
<div id="addsupermarket" style="" class=""></div>
</div>
<div id="foot" style="background-color:white; width:100%; height:auto; position:fixed; top:447px;">
<button type="button" class="btn btn-primary" style="float:right;" id="btnAdd">Add Supermarkets</button>
</div>
<script>
var data;
var checkedItems = new Map();
function loadView(options) {
var id = typeof options.id === "undefined" ? "addsupermarket" : options.id;
var cb = typeof options.callback === "undefined" ? function(){} : options.callback;
google.script.run.withSuccessHandler(function(html) {
document.getElementById("addsupermarket").innerHTML = html;
typeof options.params === "undefined" ? cb() : cb(options.params);
})[options.func]();
}
function setDataForSearch() {
checkedItems = new Map();
showSpinner();
document.getElementById("statusText").innerHTML = "Loading..."
google.script.run.withSuccessHandler(function(dataReturned) {
data = dataReturned.slice();
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
data.forEach(function(r) {
var tr = template.cloneNode(true);
var supermarketCheckColumn = tr.querySelector(".supermarketCheck");
var supermarketNameColumn = tr.querySelector(".supermarketName");
var supermarketIDColumn = tr.querySelector(".supermarketID");
var supermarketStatusColumn = tr.querySelector(".supermarketStatus");
var supermarketCheckbox = tr.querySelector(".supermarketCheckbox");
supermarketNameColumn.textContent = r[0];
supermarketIDColumn.textContent = r[1];
supermarketStatusColumn.textContent = r[2];
supermarketCheckbox.dataset.supermarketID = r[1];
searchResultsBox.appendChild(tr);
});
document.getElementById("statusText").innerHTML = "Found " + data.length + " results";
hideSpinner();
}).getDataForSearch();
}
function loadAddSupermarketView() {
loadView({func: "loadAddSupermarketView", callback: setDataForSearch});
}
loadAddSupermarketView();
document.getElementById("searchInput").addEventListener("input", inputEventHandler);
function inputEventHandler(e) {
if (e.target.matches("#searchInput")) {
search();
}
}
function showSpinner() {
document.getElementById("spinner").style.visibility = "visible";
}
function hideSpinner() {
document.getElementById("spinner").style.visibility = "hidden";
}
function search() {
var searchInput = document.getElementById("searchInput").value;
var resultsArray = data.filter(function(r) {
return (r[0].toString().toLowerCase().indexOf(searchInput.toString().toLowerCase()) !== -1 || (r[1].toString().indexOf(searchInput.toString()) !== -1));
});
document.getElementById("statusText").innerHTML = "Loading..."
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function(r) {
var tr = template.cloneNode(true);
var supermarketCheckbox = tr.querySelector(".supermarketCheckbox");
var supermarketCheckColumn = tr.querySelector(".supermarketCheck");
var supermarketNameColumn = tr.querySelector(".supermarketName");
var supermarketIDColumn = tr.querySelector(".supermarketID");
var supermarketStatusColumn = tr.querySelector(".supermarketStatus");
supermarketCheckbox.dataset.supermarketID = r[1];
supermarketNameColumn.textContent = r[0];
supermarketIDColumn.textContent = r[1];
supermarketStatusColumn.textContent = r[2];
searchResultsBox.appendChild(tr);
});
document.getElementById("statusText").innerHTML = "Found " + resultsArray.length + " results";
}
</script>
</body>
</html>
addsupermarket.html (which contains the table)
<table class="table">
<thead>
<tr>
<th scope="col">Add?</th>
<th scope="col">Name</th>
<th scope="col">ID</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody id="searchResults">
</tbody>
</table>

Related

Remove array element according to the chosen item from the list

I have a list of incomes each with its own value and its own delete icon.
When adding an income to the list, an array is filled with its values and then sum those values.
The idea is that at the time of deleting an item from the list, it will also be deleted from the array.
const txtDescripIncome = document.getElementById("descriptionIncome");
const txtIncomeValue = document.getElementById("incomeValue");
const btnAdd = document.getElementById("addIncome");
const span = document.getElementById("total-money");
const spanList = document.getElementsByClassName('badge badge-primary badge-pill');
let j;
let arrayValueIncomes = [];
deleteArray = [];
//**************************************************************************************************************************************** */
//FUNCTIONS
//****************************************************************************************************************************************
//***************add income to list********************
function addIncome() {
let descriIncome = txtDescripIncome.value;
let IncomeValue = txtIncomeValue.value;
let listItem = document.createElement("li");
let i;
listItem.className =
"list-group-item d-flex justify-content-between align-items-center";
listItem.innerHTML = `${descriIncome} <span class="badge badge-primary badge-pill">$ ${IncomeValue}</span> </i>`;
document.getElementById("listIncomes").appendChild(listItem);
sumIncomes();
txtDescripIncome.value = "";
txtIncomeValue.value = "";
for(let i = 0; i<spanList.length; i++){
spanList[i].setAttribute("data-id", i)
console.log(spanList.item(i).innerHTML)
}
//***************Delete income from the list********************
function deleteIncome() {
const list = document.querySelectorAll(".list-group-item");
let tab = [],
liIndex;
for (i = 0; i < list.length; i++) {
tab.push(list[i].innerHTML);
//console.log(tab);
}
for (let i = 0; i < list.length; i++) {
list[i].onclick = function() {
liIndex = tab.indexOf(this.innerHTML);
//console.log(this.innerHTML + "INDEX = " + liIndex);
deleting();
list[liIndex].parentNode.removeChild(list[liIndex]);
};
}
}
deleteIncome();
}
function deleteIncomeFromArray() {}
//***********Sum all Incomes************************
function sumIncomes() {
let item = txtIncomeValue.value;
arrayValueIncomes.push(parseInt(item));
let sum = arrayValueIncomes.reduce((a, b) => a + b);
span.innerHTML = sum;
}
function deleting() {
arrayValueIncomes.forEach(function (currentValue, index, array) {
let x = currentValue
//let nodo = spanList.item(x).dataset.id
let i = arrayValueIncomes.indexOf(x)
console.log(i)
arrayValueIncomes.splice(i, 1)
})
console.log(arrayValueIncomes)
}
//**************************************************************************************************************************************** */
//EVENT LISTENERS
//****************************************************************************************************************************************
btnAdd.addEventListener("click", addIncome);
/* ******************************************************************************************************************************************
CARD STYLES
*******************************************************************************************************************************************/
.title-income{
text-align: center;
}
.card{
margin-top:30px;
border-radius: 10px 10px 10px 10px;
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
}
.income-list{
margin-top:15px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/css/bootstrap.min.css" integrity="sha384-SI27wrMjH3ZZ89r4o+fGIJtnzkAnFs3E4qz9DIYioCQ5l9Rd/7UAa8DHcaL8jkWt" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-6">
<div class="card" style="width: 33rem;">
<div class="card-body">
<div class= section-income>
<div class= title-income>
<h2>Month Incomes</h2>
</div>
<div class="incomes">
<input type="text" placeholder="Income Description" id="descriptionIncome">
<input type="text" placeholder="Income Value" id="incomeValue">
<button type="button" class="btn btn-success" id="addIncome">Add</button>
</div>
<div class="income-list">
<ul class="list-group" id="listIncomes">
</ul>
</div>
<div class = total-income>
<span id = "total-money" class = total>0</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/js/bootstrap.min.js" integrity="sha384-3qaqj0lc6sV/qpzrc1N5DC6i1VRn/HyX4qdPaiEFbn54VjQBEU341pvjz7Dv3n6P" crossorigin="anonymous"></script>
</body>
</html>
For some reason the delete icon is not shown in this editor.
In the previous code it does not work correctly since at the time of removing an item, 2 or more items are removed from the array and not the specific item selected.
Looking at your implementation below code exactly does what is it supposed to be.. replace the below script block on your code.
<script>
const txtDescripIncome = document.getElementById("descriptionIncome");
const txtIncomeValue = document.getElementById("incomeValue");
const btnAdd = document.getElementById("addIncome");
const span = document.getElementById("total-money");
const spanList = document.getElementsByClassName('badge badge-primary badge-pill');
let j;
let arrayValueIncomes = [];
let total = 0;
deleteArray = [];
function addIncome() {
let descriIncome = txtDescripIncome.value;
let IncomeValue = txtIncomeValue.value;
let listItem = document.createElement("li");
let i;
listItem.className = "list-group-item d-flex justify-content-between align-items-center";
listItem.innerHTML = `${descriIncome} <span class="badge badge-primary badge-pill">$ ${IncomeValue}</span> Del</i>`;
document.getElementById("listIncomes").appendChild(listItem);
txtDescripIncome.value = "";
txtIncomeValue.value = "";
listItem.dataset.data = parseFloat(IncomeValue);
total = parseFloat(total) + parseFloat(listItem.dataset.data);
listItem.onclick = function() {
total = total - this.dataset.data;
this.parentNode.removeChild(this);
span.innerHTML = total;
console.log(total);
};
console.log(total);
span.innerHTML = total;
}
btnAdd.addEventListener("click", addIncome);
</script>

Passing a data or value from a drop down bar in a modal to a JS table

Im really new with coding. Hopefully you can help me. Really appreciate it.
So I have a modal that is supposed to pass the value to a JS table. The modal has a drop down bar and a text field. the drop down got its values from a passed json via document.getElemetById. So I want to pass the chosen value from the dropdown and the value of the text field to the JS table.
so I've also tried this and does not work.
function trigData() {
var table = document.getElementById('container-2');
var i;
for (var i = 0; i < 2; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.setAttribute("id", "equipment");
td2.setAttribute("id", "quantity");
}
var text1 = document.getElementById("equipment").innerHTML = td1.value;
var text1 = document.getElementById("equipment").innerHTML = td1.value;
// ALSO TRIED THIS
//var text1 = document.createTextNode(td1);
//var text2 = document.createTextNode(td2);
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
/////////////// BELOW IS THE WHOLE CODE ////////////////
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js">
</script>
<style>
.container-2 {
position: absolute;
top: 10%;
left: 5%;
width: 45%;
height: 30%;
margin-top: 15px;
border: 3px solid #d9d9d9;
background-color: #f2f2f2;
overflow-x: scroll;
overflow-y: scroll;
}
.container-2 table, th, td {
width: 32.5%;
height: 10px;
border: 1px solid #d9d9d9;
border-collapse: collapse;
font-size: 15px;
}
th, td {
padding: 0;
}
</style>
</head>
<body>
<div class="borrow-list-area">
<table class="container-2" id="container-2">
<thead>
<tr>
<style>th,td{text-align:center;}
</style>
<th>Equipment</th>
<th>Quantity</th>
</tr>
</thead>
<script>
// THIS IS CODE I'M HAVING TROUBLE WITH
function trigData() {
var table = document.getElementById('container-
2');
var i;
for (var i = 0; i < 2; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.setAttribute("id", "equipment");
td2.setAttribute("id", "quantity");
}
var text1 = document.getElementById("equipment").innerHTML = td1;
var text2 = document.getElementById("quantity").innerHTML = td1;
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
</script>
<tbody></tbody>
</table>
</div>
<div class="container" >
<!-- Trigger the modal with a button -->
<button type="button" class="button-1 btn-lg" data-toggle="modal" data-target="#myModal" style="width: 26%; margin:0; height: 40px; font-size: 100%;">Choose Equipment</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<p>Choose An Equipment Below</p>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>Available Equipments</p>
<div class="form-inline">
<select name="dpdwn" class="drop-down">
<option selected="" disabled="">Select Equipment</option>
<option id="a" value="dpdwn-1"></option>
<option id="b" value="dpdwn-2"></option>
<option id="c" value="dpdwn-3"></option>
</select>
<br><br>
<input type="text" id="qnty-1" class="form-control" placeholder="Quantity" name="quantity" style="width:24%;"><br/>
<script>
var myObj, myJSON, text, obj;
/////////////////////////////// DISPLAY ///////////////////////////////////
// Storing data:
myObj = {
"cars" : [ "HONDA", "FIAT", "BMW" ]
};
myJSON = JSON.stringify(myObj);
localStorage.setItem("drop-down", myJSON);
// Retrieving data:
text = localStorage.getItem("drop-down");
obj = JSON.parse(text);
document.getElementById("a").innerHTML = obj.cars[0];
//document.getElementById("a").value = obj.id;
document.getElementById("b").innerHTML = obj.cars[1];
document.getElementById("c").innerHTML = obj.cars[2];
/////////////////////////////////// PASSING VALUES //////////////////////////////////////
function passValue1(a) {
text = localStorage.getItem("drop-down");
obj = JSON.parse(text);
var q = "dpdwn-1";
var b = "dpdwn-2";
var c = "dpdwn-3";
var e = document.getElementById(a);
alert(a.value);
if(a.value == q){
document.getElementById("equipment").innerHTML = obj.cars[0];
} else if(a.value == b){
document.getElementById("equipment").innerHTML = obj.cars[1];
} else {
document.getElementById("equipment").innerHTML = obj.cars[2];
}
}
function passValue2(b) {
document.getElementById("quantity").innerHTML = document.getElementById("qnty-1").value;
}
</script>
<br/><br/>
</div>
</div>
<div class="modal-footer">
<input class="submit-3" type = "submit" value = "Submit" name= "submit-2" onclick="trigData(); passValue1(dpdwn); passValue2(document.getElementById('qnty-1').value)"data-dismiss="modal" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
So I really need the output to be displayed on the JS table and would increment if ever same item is chosen. so far it wont show up anything or it will show up on the cell "[object HTMLTableCellElement]".

Add textboxes along with text to a table (tbody) in HTML

I am stuck in a problem where I have to create text boxes dynamically into the table cell. Along with the data which I am fetching from the DB.
It should be something like:
Number of rows are dynamic and I am able to generate it using Array. I am capturing all values into the array of records for each row and pushing it into the table. But I don't know what to do to add empty text boxes.
I was thinking if I can add "textboxes" to the array and insert along with text to the table cell. I am not sure what other options available.
I am open to answer any queries to you which might help me to get the answer.
EDIT:
Below is the code which I used to generate table:
function generateTable(fundDetails){
var tbody_holder = document.getElementById("tbody_holder");
for(var row = 0; row < fundDetails.length; row++){
var tr = document.createElement("tr");
for(var col = 0; col < fundDetails[row].length; col++){
var td = document.createElement("td");
var tn = document.createTextNode(fundDetails[row][col]);
td.appendChild(tn);
tr.appendChild(td);
}
tbody_holder.appendChild(tr);
}
}
fundDetail is a 2D array. Each element in array contains all the data for the one row of table. Next array element contains data for next row. I want to insert text boxes in each rows.
TIA
I think it will be your answer for creating the records dynamically.
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-control" content="no-cache">
<script src="jquery/jquery-1.10.2.js"></script>
<script src="jquery/canvasjs.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="font-awesome/css/font-awesome.css">
<script src="jquery/jquery-ui.js"></script>
<script type="text/javascript" src="jquery/html2canvas.min.js"></script>
<script type="text/javascript" src="jquery/jquery.plugin.html2canvas.js"></script>
<link rel="stylesheet" href="jquery/jquery-ui.css">
<style>
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="text"], input[type="number"] {
border: none;
}
tbody tr{
background:#f7f7f7;
}
.navbar{
border-radius:0px !important;
border:none;
}
thead{
background:#8b99a0;
color:white;
}
.navbar{
background:#323E4E;
}
table{
border-radius:4px !important;
}
a.canvasjs-chart-credit {
display: none;
}
#chartContainer{
border-bottom:1px dashed #8b99a0;
border-right:1px dashed #8b99a0;
}
.stuck{
position:fixed;
z-index:100;
width:100%;
top:0;
}
hr {
margin-top: 0px;
margin-bottom: 0px;
}
</style>
<script>
$(window).scroll(function() {
if ($(window).scrollTop() > 50) {
$("#bar").addClass('stuck');
} else {
$('#bar').removeClass('stuck');
}
});
</script>
</head>
<body>
<nav class="navbar navbar-inverse" id="bar">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img src="images/records.png" style="width:50px;height:45px;float:left;" class="navbar-logo">
<a class="navbar-brand" href="#" title="calculation">Student Records</a>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2 style="text-align:center;color: #323E4E;">Student marksheet</h2>
</div>
<div class="col-md-12" style="margin-bottom:2px;">
<div class="col-md-2">
<button class="btn btn-primary" id="addbtn" style="float:left;margin-right:10px;"><i class="fa fa-user-plus" aria-hidden="true"></i> Add Row</button>
</div>
<div class="col-md-8">
<div class="form-group">
<input type="text" class="search form-control" id="search" placeholder="What you looking for?" style="box-shadow:5px 5px 5px #f7f7f7;">
</div>
</div>
<div class="col-md-2">
<button class="btn btn-primary" id="btnExport" style="float:right;"><a style="text-decoration:none;color:#fff;"><i class="fa fa-download"></i> Download</span></a></button>
</div>
</div>
<div class="col-md-12" style="margin-bottom:30px !important;">
<div class="col-md-10">
<div id="dvData">
<table class="table table-hover" id="tblData">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Mark1</th>
<th>Mark2</th>
<th>Total</th>
<th>Average</th>
<th>Status</th>
</tr>
</thead>
<tbody id="frm">
</tbody>
</table>
</div>
</div>
<div class="col-md-2">
<label>Result Chart</label>
<hr>
<div id="chartContainer" style="width:100%;height:200px;"></div>
</div>
</div>
</div>
</div>
</body>
<script>
var aa=0, z=1, numb=1, id="ping";
var x, ab ,bc,cd,tr,ty,tg,we ,er;
var id1,id2,id0,stat="mark",num="1";
var mnc="avg",mno="total", abcd=1;
var msg="status",pa=0,fa=0, stanum;
$("#addbtn").click(function(e){
var i=aa;
var zz=z+aa;
for(i;i<zz;i++){
var head= document.createElement("TR");
ab="tear";
bc=zz;
cd=ab.concat(bc);
head.setAttribute("id",cd);
document.getElementById("frm").appendChild(head);
var did= document.createElement("TD");
var pin=id.concat(numb);
did.setAttribute("id",pin);
document.getElementById(cd).appendChild(did);
document.getElementById(pin).innerHTML=numb;
numb++;
for(var p=0;p<6;p++){
if(p<3){
var lab= document.createElement("TD");
tr="tead";
ty=p;
we=zz;
er=tr.concat(ty);
tg=er.concat(we);
lab.setAttribute("id",tg);
document.getElementById(cd).appendChild(lab);
}else if(p==3)
{
var lab= document.createElement("TD");
tr="tead";
ty=p;
we=zz;
er=tr.concat(ty);
tg=er.concat(we);
lab.setAttribute("id",tg);
var ctot=mno.concat(abcd);
lab.setAttribute("id",ctot);
document.getElementById(cd).appendChild(lab);
}else if(p==4)
{
var lab= document.createElement("TD");
tr="tead";
ty=p;
we=zz;
er=tr.concat(ty);
tg=er.concat(we);
lab.setAttribute("id",tg);
var cpo=mnc.concat(abcd);
lab.setAttribute("id",cpo);
document.getElementById(cd).appendChild(lab);
}else if(p==5)
{
var lab= document.createElement("TD");
var meg=msg.concat(i);
lab.setAttribute("id",meg);
document.getElementById(cd).appendChild(lab);
}
if(p==0)
{
x= document.createElement("INPUT");
x.setAttribute("type","text");
id0=stat.concat(num);
num++;
x.setAttribute("id",id0);
document.getElementById(tg).appendChild(x);
}else if(p==1)
{
x= document.createElement("INPUT");
x.setAttribute("type","number");
id1=stat.concat(num);
num++;
x.setAttribute("id",id1);
document.getElementById(tg).appendChild(x);
}else if(p==2)
{
x= document.createElement("INPUT");
x.setAttribute("type","number");
id2=stat.concat(num);
num++;
x.setAttribute("id",id2);
document.getElementById(tg).appendChild(x);
}
}
}
abcd++;
aa++;
});
var xx;
$("#tblData").change(function(e){
var n=1;var qq=0;xx=0;
for(var rr=1;rr<=aa;rr++){
var m0=stat.concat(n);
n++;
var m1=stat.concat(n);
n++;
var m2=stat.concat(n);
n++;
var az=document.getElementById(m0).value;
document.getElementById(m0).innerHTML=az;
var a=document.getElementById(m1).value;
document.getElementById(m1).innerHTML=a;
var b=document.getElementById(m2).value;
document.getElementById(m2).innerHTML=b;
if(a=="")
{
a=0;
}else if(b==""){
b=0;
}
else{}
var c=Number(a)+Number(b);
var d=(Number(a)+Number(b))/2;
var mp=mno.concat(rr);
document.getElementById(mp).innerHTML=c;
var cp=mnc.concat(rr);
document.getElementById(cp).innerHTML=d;
stanum=msg.concat(qq);
if((a<50)||(b<50)){
document.getElementById(stanum).innerHTML="Fail";
qq++;
}else{
document.getElementById(stanum).innerHTML="Pass";
qq++;
}
}
xx=qq;
});
$("#tblData").change(function(e){
fa=0,pa=0;
var county=$('#tblData tr').length;
for(var mob=0;mob<county-1;mob++){
var mom=msg.concat(mob);
if(document.getElementById(mom).innerHTML=="Pass"){
pa++;
}
if(document.getElementById(mom).innerHTML=="Fail"){
fa++;
}
}
var chart = new CanvasJS.Chart("chartContainer",
{
animationEnabled: true,
title:{
text: "students vs pass / fail"
},
data: [
{
type: "column", //change type to bar, line, area, pie, etc
dataPoints: [
{ label: "pass", y: pa },
{ label: "fail", y: fa }
]
}
]
});
chart.render();
});
</script>
<script type="text/javascript">
$("#resbtn").click(function(e){
html2canvas($("#tblData"), {
onrendered: function(canvas) {
theCanvas = canvas;
canvas.toBlob(function(blob) {
saveAs(blob, "pretty image.png");
});
}
});
});
</script>
<script>
$(document).ready(function()
{
$('#search').keyup(function()
{
searchTable($(this).val());
});
});
function searchTable(inputVal)
{
var table = $('#tblData');
table.find('tr').each(function(index, row)
{
var allCells = $(row).find('td');
if(allCells.length > 0)
{
var found = false;
allCells.each(function(index, td)
{
var regExp = new RegExp(inputVal, 'i');
if(regExp.test($(td).text()))
{
found = true;
return false;
}
});
if(found == true)$(row).show();else $(row).hide();
}
});
}
</script>
<Script>
$("#btnExport").click(function (e) {
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth() + 1;
var year = dt.getFullYear();
var hour = dt.getHours();
var mins = dt.getMinutes();
var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
//creating a temporary HTML link element (they support setting file names)
var a = document.createElement('a');
//getting data from our div that contains the HTML table
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('dvData');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'exported_table_' + postfix + '.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
});
</script>
</html>

JQuery Remove not removing specified div

I have a small page on which you can add squares of different colors to a div with a button. After adding them, you can remove them by double clicking any of the squares created.
My code works well, when adding elements. However when I want to remove a square, I just get to remove one and after that I can´t make the element disappear on HTML even though the counter does decrease. I´m a doing something wrong with the remove() function? Right now I´m just focusing on the blue (Azul) color.
Here´s my code
https://jsfiddle.net/kdwyw0mc/
var azules = 0;
var rojos = 0;
var amarillos = 0;
var verdes = 0;
function eliminar(cuadro){
azules = parseInt(jQuery('#num-azules').text());
verdes = parseInt(jQuery('#num-verdes').text());
rojos = parseInt(jQuery('#num-rojos').text());
amarillos = parseInt(jQuery('#num-amarillos').text());
if(cuadro[0].classList[1]=='blue'){
azules = azules -1;
}
else if(cuadro[0].classList[1]=='red'){
rojos--;
}
else if(cuadro[0].classList[1]=='yellos'){
amarillos--;
}
else if(cuadro[0].classList[1]=='green'){
verdes--;
}
cuadro.remove();
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
}
function agregar(){
jQuery('span#num-azules').val(azules);
var numCuadros = jQuery("#numero").val();
var color = $('#color option:selected').text();
for( i = 0; i< numCuadros; i++){
if(color=='Azul'){
/*jQuery(".square").append(function(){
return jQuery('<div class="square blue"> </div>').ondblclick(eliminar);
})*/
var newSquare = jQuery('<div class="square blue"> </div>')
var a = jQuery(".squares").append(newSquare);
newSquare.dblclick(function(){eliminar(newSquare);})
azules += 1;
}
else if(color=='Rojo'){
jQuery(".squares").append('<div class="square red"> </div>')
rojos+= 1;
}
else if(color=='Amarillo'){
jQuery(".squares").append('<div class="square yellow"> </div>')
amarillos+= 1;
}
else if(color=='Verde'){
jQuery(".squares").append('<div class="square green"> </div>')
verdes+= 1;
}
}
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
}
/*
* jQuery("#agregar").click(function(){
agregar();
});
VS
jQuery("#agregar").click(agregar());
* */
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
jQuery("#agregar").click(function(){
agregar();
});
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="styles/reset.css"/>
<link rel="stylesheet" href="styles/main.css"/>
</head>
<body>
<div class="main-content">
<div class="toolbar">
Numero Cuadrados: <input id="numero"type="text"/>
<select id="color" name="color">
<option value="azul">Azul</option>
<option value="rojo">Rojo</option>
<option value="amarillo">Amarillo</option>
<option value="verde">Verde</option>
</select>
<button id="agregar">Agregar</button>
</div>
<div class="squares">
</div>
<div class="numeros">
<p>Azules: <span id="num-azules">0</span> </p>
<p>Rojos: <span id="num-rojos">0</span></p>
<p>Verde: <span id="num-verdes">0</span></p>
<p>Amarillo: <span id="num-amarillos">0</span></p>
</div>
</div>
<script src="scripts/jquery-1.11.3.min.js"></script>
<script src="scripts/main.js"></script>
</body>
</html>
This is an inefficient way of registering / listening to events, it is better to delegate the event handling to a wrapper (parent) container:
$("#container").on("dblclick", ".square", function(){
$(this).remove();
)};
on works for dynamically created elements; since the container was already in the DOM, it can continue listening to events coming from any other, newly created child element that has class .square.
http://api.jquery.com/on/
Edit:
One way of solving the counter problem would be to do something like this:
var StateObj = function(){
this.counter = 0;
this.arrSquares = [];
this.increaseCounter = function(){
this.counter += 1;
},
this.decreaseCounter = function(){
this.counter -= 1;
},
this.addSquare = function(id, color){
this.arrSquares.push({id: id, color: color});
},
this.getSquareById = function(id){
return square = $.grep(this.arrSquares, function(){ return id == id; });
}
}
var stateObj = newStateObj();
$("#container").on("dblclick", ".square", function(e){
$(this).remove();
var id = $(e.currentTarget).attr("id");
stateObj.increaseCounter();
console.log(stateObj.counter);
)};

How to not insert duplicate images?

So what I have done is that, I have created a function that retrives data(images) from the database using XMLHttpRequest and appends it to td every 5000 milliseconds. Now as they are appended every 5000 milliseconds, if the data retrieved is not changed then it keeps appending the same data again and again. To stop it I attached custom attributes to the images with their IDs but I am not sure how would I stop it from appending duplicated items. This is my JS:
function getAlbumImages() {
var xhr2 = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr2.open('GET', 'admin/images_data.php');
xhr2.onreadystatechange = function(e) {
if(xhr2.readyState == 4 && xhr2.status == 200) {
var album_photos = JSON.parse(xhr2.responseText);
for(var i = 0; i < album_photos.length; i++) {
var td = document.createElement('td');
var imagewrap = document.createElement('div');
imagewrap.className = "image-wrap";
var imagemenu = document.createElement('div');
imagemenu.className = "image-menu";
var imagemenuimg1 = document.createElement('img');
imagemenuimg1.src = "img/edit_img.png";
var imagemenuimg2 = document.createElement('img');
imagemenuimg2.src = "img/close.png";
var imagewrapimg = document.createElement('img');
imagewrapimg.className = "thumbnail";
imagewrapimg.src = "admin/album_photos/" + album_photos[i].Image_Path;
imagewrapimg.setAttribute("data-image-id", album_photos[i].Image_ID);
document.getElementById("tiare").appendChild(td);
td.appendChild(imagewrap);
imagewrap.appendChild(imagemenu);
imagemenu.appendChild(imagemenuimg1);
imagemenu.appendChild(imagemenuimg2);
imagewrap.appendChild(imagewrapimg);
}
}
}
xhr2.send(null);
}
setInterval(function(){
getAlbumImages();
}, 5000);
And the markup:
<html>
<head>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- <div class="big_image" id="drop_zone">
<img src="" id="big_img" />
</div -->
<div class="images_holder">
<div class="header">
Album Name - Photo Album
<span class="close"><img src="img/close.png" /></span>
</div>
<div class="body">
<table width="80%">
<tr id="tiare">
</tr>
</table>
</div>
</div>
<div id="drop_zone">
Drag/Drop images to upload.
</div>
<div style="height: 30px; width: 80%; color: white; text-align: center; margin: 0 auto;">
<p id="progress_bar" style="width: 0%; background-color: red;"></p>
</div>
<script src="js/script.js"></script>
</body>
</html>
This is what happens the first time:
And this is what happens afterwards:
See the duplicated images
How can I stop it from appending the duplicated? Thanks in advance. :)
P.S: NO JQUERY ALLOWED. :)
Just check if instance with same ID or URL is at page before insert
if(document.querySector('div.thumbnail[data-image-id="' + album_photos[i].Image_ID + '"]')){
continue;
}
Or save list of all inserted id's in memory ( as array or object { id: url } ) and check if this item already loaded

Categories

Resources