how to restrict duplicate data in dynamic table - javascript

i just hit a demo api with link and created a dynamic table and in every click of parameter a new row is inserted with it, i just want to resitrict duplicate entry from table.
$(document).ready(function () {
//count = 1;
var counter=1,flag=0;
$("#api").click(function () {
var index = ($("#para").val());
if (index == "") {
alert("Please input data");
return false;
}
else{
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/'+index,
type: 'GET',
dataType: 'json',
crossDomain: true,
success: function (data, textStatus, xhr) {
console.log(data);
var tr = [];
if(flag==0){
mytable = $('<table></table>').attr({ id: "basicTable", class:"basicTable1" });
//for (var i = 0; i < count; i++) {
let ab = $('<h1>API Data</h1>').appendTo("#h");
let row = $('<tr></tr>').appendTo(mytable);
let row1 = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<th></th>').text(key).appendTo(row);
$('<td></td>').text(val).appendTo(row1);
});
let row2 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row1);
flag=1;
counter++;
//}
mytable.appendTo("#data");
}
else{
//for (var i = 0; i < count; i++) {
let row = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<td></td>').text(val).appendTo(row);
});
let row1 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row);
counter++;
//}
mytable.appendTo("#data");
}
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
alert("No Record Found");
}
});
}
});
});
function removeFun(a){
$("#row"+a).remove();
}
var textbox = $("#data");
textbox.change(function() {
$("#basicTable").find("td").each(function(){
if($(this).html()==textbox.val()){
alert(textbox.val());
};
})
});
.h1{
color: orange;
margin:30px;
}
.h2{
margin-top: 20px;
}
table, th, td {
border: 2.5px solid black;
align-content: center;
}
table{
width: 80%;
text-align: center;
}
th{
height: 50px;
align-content: right;
background-color: orange;
}
th:hover {background-color: #3e8e41}
th,td{
width: 30%;
}
.button1 {
padding: 10px 15px;
font-size: 14px;
text-align: center;
cursor: pointer;
outline: none;
color: #fff;
background-color: orange;
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
}
.button1:hover {background-color: #3e8e41}
.button1:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
<!DOCTYPE html>
<html>
<head>
<title>Api hit with JSON</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<center><u class="h1">AJAX</u> api with JSON</center>
<center>
<div class="h2">
<label>Enter the parameter</label>
<input type="number" name="" id="para">
<button id="api">Submit</button>
</div>
<div id="h"></div>
<div id="data"></div>
</center>
</body>
</html>
This is my file, I hit the demo api with link and get the data to dynamic table but I want to restrict duplicate files in the dynamic table.
$(document).ready(function () {
//count = 1;
var counter=1,flag=0;
$("#api").click(function () {
var index = ($("#para").val());
if (index == "") {
alert("Please input data");
return false;
}
else{
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/'+index,
type: 'GET',
dataType: 'json',
crossDomain: true,
success: function (data, textStatus, xhr) {
console.log(data);
var tr = [];
if(flag==0){
mytable = $('<table></table>').attr({ id: "basicTable", class:"basicTable1" });
//for (var i = 0; i < count; i++) {
let ab = $('<h1>API Data</h1>').appendTo("#h");
let row = $('<tr></tr>').appendTo(mytable);
let row1 = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<th></th>').text(key).appendTo(row);
$('<td></td>').text(val).appendTo(row1);
});
let row2 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row1);
flag=1;
counter++;
//}
mytable.appendTo("#data");
}
else{
//for (var i = 0; i < count; i++) {
let row = $('<tr id="row'+counter+'" ></tr>').appendTo(mytable);
$.each(data, function(key, val) {
$('<td></td>').text(val).appendTo(row);
});
let row1 = $('<button class="button1" id="button'+ counter+'" onclick=removeFun('+ counter+')>remove Row</button>').appendTo(row);
counter++;
//}
mytable.appendTo("#data");
}
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
alert("No Record Found");
}
});
}
});
});
function removeFun(a){
$("#row"+a).remove();
}

first you need to remove duplicates from your "data"
var GroupByColumn = function (SourceData, columnName) {
var Unique = {};
var groupByColumn = columnName;
var tempData = SourceData;
for (var i = 0; i < tempData.length; i++) {
if (!Unique[tempData[i][groupByColumn]])
Unique[tempData[i][groupByColumn]] = [];
Unique[tempData[i][groupByColumn]].push(tempData[i]);
}
return Unique;
}
by using above function you can find a unique data
var z= [
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
}
]
GroupByColumn(z,"id")
GroupByColumn(z,"title")
GroupByColumn(z,"completed")
GroupByColumn(z,"userId")
depepends on your need it will return your data. hope this will be helpful

Related

Table data export with identifier

How can I export this HTML table data in a way, that the exported data look exactly as the initial data.
The array data[] is the source for the table below. The button dataToArray exports this HTML table data back to an array. I struggle with the format as I need the data identifier, in the array, too.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Table Test</title>
<!-- d3.js framework -->
<script src="https://d3js.org/d3.v6.js"></script>
<!-- jquery import-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- fontawesome stylesheet https://fontawesome.com/ -->
<script src="https://kit.fontawesome.com/39094309d6.js" crossorigin="anonymous"></script>
</head>
<style>
#myTable {
border-collapse: collapse;
}
#myTable td {
border: 1px solid black;
padding: 8px;
}
#delRow {
width: auto;
height: 30px;
}
</style>
<body>
<table id="myTable">
<th>
Property
</th>
<th>
Value
</th>
<tbody>
<!-- filled by script -->
</tbody>
</table>
<button id="dataToArray">dataToArray</button>
<script>
data = [
{
"property": "animal",
"value": "dog"
},
{
"property": "car",
"value": "audi"
},
{
"property": "snacks",
"value": "chips"
}
]
//populate table
var myTable = document.getElementById("myTable")
for (var i = 0; i < data.length; i++ ) {
var row = `<tr>
<td>${data[i].property}</td>
<td>${data[i].value}</td>
</tr>`
myTable.innerHTML += row
}
//get table data
var dataToArray = document.getElementById("dataToArray")
dataToArray.addEventListener("click", function() {
console.clear()
console.log("data before export:")
console.log(data)
var exportData = []
$("table#myTable tr").each(function() {
var rowDataArray = []
var actualData = $(this).find("td");
if (actualData.length > 0) {
actualData.each(function() {
rowDataArray.push($(this).text());
});
exportData.push(rowDataArray)
};
})
console.log("data after export:")
console.log(exportData)
})
</script>
</body>
</html>
Here is dynamic way (works even for more than two headers without changing the export code):
First get all headers dynamically (not hard code) by this line:
var headers = $("table#myTable th").map(function () {
return this.innerText;
}).get();
And then in export time do like this:
var object = {};
headers.forEach((data, index) => {
object[data] = actualData[index].innerText;
})
exportData.push(object)
data = [
{
"property": "animal",
"value": "dog"
},
{
"property": "car",
"value": "audi"
},
{
"property": "snacks",
"value": "chips"
}
]
//populate table
var myTable = document.getElementById("myTable")
for (var i = 0; i < data.length; i++) {
var row = `<tr>
<td>${data[i].property}</td>
<td>${data[i].value}</td>
</tr>`
myTable.innerHTML += row
}
//get table data
var dataToArray = document.getElementById("dataToArray")
dataToArray.addEventListener("click", function () {
var headers = $("table#myTable th").map(function () {
return this.innerText;
}).get();
console.clear()
console.log("data before export:")
console.log(data);
var exportData = []
$("table#myTable tr").each(function (e,i) {
var rowDataArray = []
var actualData = $(this).find("td");
if (actualData.length > 0) {
var object = {};
headers.forEach((data, index) => {
object[data] = actualData[index].innerText;
})
exportData.push(object)
};
})
console.log("data after export:")
console.log(exportData)
})
#myTable {
border-collapse: collapse;
}
#myTable td {
border: 1px solid black;
padding: 8px;
}
#delRow {
width: auto;
height: 30px;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<table id="myTable">
<th>
Property
</th>
<th>
Value
</th>
<tbody>
<!-- filled by script -->
</tbody>
</table>
<button id="dataToArray">dataToArray</button>
You must define rowDataArray as new Object
I change your code only at this part:
var exportData = []
$("table#myTable tr").each(function() {
var rowDataArray = []
var actualData = $(this).find("td");
if (actualData.length > 0) {
actualData.each(function() {
rowDataArray.push($(this).text());
});
exportData.push(rowDataArray)
};
})
and change it with:
var exportData = []
$("table#myTable tr").each(function() {
var rowDataObject= new Object;
var actualData = $(this).find("td");
if (actualData.length > 0) {
rowDataObject.property = actualData[0].innerText;
rowDataObject.value= actualData[1].innerText;
exportData.push(rowDataObject)
};
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Table Test</title>
<!-- d3.js framework -->
<script src="https://d3js.org/d3.v6.js"></script>
<!-- jquery import-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- fontawesome stylesheet https://fontawesome.com/ -->
<script src="https://kit.fontawesome.com/39094309d6.js" crossorigin="anonymous"></script>
</head>
<style>
#myTable {
border-collapse: collapse;
}
#myTable td {
border: 1px solid black;
padding: 8px;
}
#delRow {
width: auto;
height: 30px;
}
</style>
<body>
<table id="myTable">
<th>
Property
</th>
<th>
Value
</th>
<tbody>
<!-- filled by script -->
</tbody>
</table>
<button id="dataToArray">dataToArray</button>
<script>
data = [
{
"property": "animal",
"value": "dog"
},
{
"property": "car",
"value": "audi"
},
{
"property": "snacks",
"value": "chips"
}
]
//populate table
var myTable = document.getElementById("myTable")
for (var i = 0; i < data.length; i++ ) {
var row = `<tr>
<td>${data[i].property}</td>
<td>${data[i].value}</td>
</tr>`
myTable.innerHTML += row
}
//get table data
var dataToArray = document.getElementById("dataToArray")
dataToArray.addEventListener("click", function() {
console.clear()
console.log("data before export:")
console.log(data)
var exportData = []
$("table#myTable tr").each(function() {
var rowDataObject= new Object;
var actualData = $(this).find("td");
if (actualData.length > 0) {
rowDataObject.property = actualData[0].innerText;
rowDataObject.value= actualData[1].innerText;
exportData.push(rowDataObject)
};
})
console.log("data after export:")
console.log(exportData)
})
</script>
</body>
</html>

HTML Input doesn't allow double digits to be typed in from keyboard

I'm making a basic calculator and so far it "works". Users can only enter in a single digit from their keyboard. If they want to use double digits they're going to have to use the arrows in the text box. How can I make it so that users can enter in double digit numbers? If the user tries to type in double digit numbers the second number only get stored (so typing in 25 will only store 5)
// Base Variables
let result = 0;
let numb1 = 0;
let numb2 = 0;
let firstNumberEntered = false;
//This will be rewritten
let calculationDescription = `${numb1} + ${numb2}`;
document.querySelector('#input-number').addEventListener('keypress', numbersInput);
function numbersInput(e) {
if (!firstNumberEntered && e.key === 'Enter') {
numb1 = document.getElementById("input-number").value;
firstNumberEntered = true;
document.getElementById("input-number").innerHTML = "";
} else if (firstNumberEntered && e.key === 'Enter') {
numb2 = document.getElementById("input-number").value;
firstNumberEntered = false;
console.log(`${numb1} and ${numb2}`);
}
document.getElementById("input-number").value = "";
}
document.querySelector("#btn-add").addEventListener('click', sumNumbs);
document.querySelector("#btn-subtract").addEventListener('click', subtractNumbs);
document.querySelector("#btn-multiply").addEventListener('click', multiplyNumbs);
document.querySelector("#btn-divide").addEventListener('click', divideNumbs);
function sumNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final + numb2Final;
calculationDescription = `${numb1} + ${numb2}`;
outputResult(result, calculationDescription);
}
function subtractNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final - numb2Final;
calculationDescription = `${numb1} - ${numb2}`;
outputResult(result, calculationDescription);
}
function multiplyNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final * numb2Final;
calculationDescription = `${numb1} x ${numb2}`;
outputResult(result, calculationDescription);
}
function divideNumbs() {
let numb1Final = parseInt(numb1);
let numb2Final = parseInt(numb2);
result = numb1Final / numb2Final;
calculationDescription = `${numb1} / ${numb2}`;
outputResult(result, calculationDescription);
}
<section id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
</div>
</section>
All this does is grab the elements on the HTML page and put them into variables and send info back to be displayed
const userInput = document.getElementById('input-number');
const addBtn = document.getElementById('btn-add');
const subtractBtn = document.getElementById('btn-subtract');
const multiplyBtn = document.getElementById('btn-multiply');
const divideBtn = document.getElementById('btn-divide');
const currentResultOutput = document.getElementById('current-result');
const currentCalculationOutput = document.getElementById('current-calculation');
function outputResult(result, text) {
currentResultOutput.textContent = result;
currentCalculationOutput.textContent = text;
}
Not sure if providing my CSS is necessary, but let me know and I'll make a change.
I just started learning JavaScript recently. I watched a few videos on a Udemy tutorial on doing this project, but I stopped watching and tried to figure the rest out myself.
What I did try doing was adding maxlength="6" to my HTML input element, but that didn't work.
function numbersInput(e) {
if(!firstNumberEntered && e.key === 'Enter') {
numb1 = document.getElementById("input-number").value;
firstNumberEntered = true;
document.getElementById("input-number").innerHTML = "";
document.getElementById("input-number").value = "";
}
else if(firstNumberEntered && e.key === 'Enter') {
numb2 = document.getElementById("input-number").value;
firstNumberEntered = false;
console.log(`${numb1} and ${numb2}`);
document.getElementById("input-number").value = "";
}
}
Add document.getElementById("input-number").value = "";
to the end of both if statements and remove from the end of the function
Here's my own basic calculator using HTML, CSS, and javascript only.
To be able to input one or more digit numbers, use arrays to function as storage of those numbers chosen and for your chosen arithmetic operation as well.
please see my source code for a clearer grasp of my idea.
//index.html
<!DOCTYPE html>
<html>
<head>
<title>My HTML/CSS/JS Calculator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="outer-container">
<div class="items" id="items"></div>
<div class="calc-screen">
<div id="screen"></div>
</div>
<div class="keys-container">
<button type="button" class="keys" id="opm" onclick="opm()">*</button>
<button type="button" class="keys" id="opd" onclick="opd()">/</button>
<button type="button" class="keys" id="opa" onclick="opa()">+</button>
<button type="button" class="keys" id="ops" onclick="ops()">-</button>
<button type="button" class="keys" id="num9" onclick="num9()">9</button>
<button type="button" class="keys" id="num8" onclick="num8()">8</button>
<button type="button" class="keys" id="num7" onclick="num7()">7</button>
<button type="button" class="keys" id="num6" onclick="num6()">6</button>
<button type="button" class="keys" id="num5" onclick="num5()">5</button>
<button type="button" class="keys" id="num4" onclick="num4()">4</button>
<button type="button" class="keys" id="num3" onclick="num3()">3</button>
<button type="button" class="keys" id="num2" onclick="num2()">2</button>
<button type="button" class="keys" id="num1" onclick="num1()">1</button>
<button type="button" class="keys" id="num0" onclick="num0()">0</button>
<button type="button" class="keys" id="del" onclick="del()">Del</button>
<button type="button" class="keys" id="clr" onclick="clr()">Clr</button>
<button type="submit" class="keys" id="equals" onclick='equals()'>=</button>
</div>
</div>
<script type="text/javascript" src="js/js.js"></script>
</body>
</html>
//js.js
var item1, op, item2, arr1, arr2, text, x, prod, qout, sum, diff, a, b, c;
item1, item2, op = '';
arr1 = [];
arr2 = [];
function num9() {
if (op=='') {
arr1.push(document.getElementById("num9").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num9").innerHTML);
arr2Function();
}
}
function num8() {
if (op=='') {
arr1.push(document.getElementById("num8").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num8").innerHTML);
arr2Function();
}
}
function num7() {
if (op=='') {
arr1.push(document.getElementById("num7").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num7").innerHTML);
arr2Function();
}
}
function num6() {
if (op=='') {
arr1.push(document.getElementById("num6").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num6").innerHTML);
arr2Function();
}
}
function num5() {
if (op=='') {
arr1.push(document.getElementById("num5").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num5").innerHTML);
arr2Function();
}
}
function num4() {
if (op=='') {
arr1.push(document.getElementById("num4").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num4").innerHTML);
arr2Function();
}
}
function num3() {
if (op=='') {
arr1.push(document.getElementById("num3").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num3").innerHTML);
arr2Function();
}
}
function num2() {
if (op=='') {
arr1.push(document.getElementById("num2").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num2").innerHTML);
arr2Function();
}
}
function num1() {
if (op=='') {
arr1.push(document.getElementById("num1").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num1").innerHTML);
arr2Function();
}
}
function num0() {
if (op=='') {
arr1.push(document.getElementById("num0").innerHTML);
arr1Function();
}
else {
arr2.push(document.getElementById("num0").innerHTML);
arr2Function();
}
}
function opm() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("opm").innerHTML;
op = '*';
console.log(op);
}
}
function opd() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("opd").innerHTML;
op = '/';
console.log(op);
}
}
function opa() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("opa").innerHTML;
op = '+';
console.log(op);
}
}
function ops() {
if (arr1=='') {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
else if (op!='' && arr2!='') {
console.log("press equal sign");
}
else {
document.getElementById("screen").innerHTML = document.getElementById("ops").innerHTML;
op = '-';
console.log(op);
}
}
function equals() {
a = parseInt(item1); b = parseInt(item2);
if (op == '*') {
prod = a * b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+' =';
c = prod;
document.getElementById("screen").innerHTML = c;
console.log('product: '+c);
result(c);
}
else if (op == '/') {
qout = a / b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+' =';
c = qout;
document.getElementById("screen").innerHTML = c;
console.log('qoutient: '+c);
result(c);
}
else if (op == '+') {
sum = a + b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+' =';
c = sum;
document.getElementById("screen").innerHTML = c;
console.log('sum: '+c);
result(c);
}
else if (op == '-') {
diff = a - b;
document.getElementById("items").innerHTML = a+' '+op+' '+b+ ' =';
c = diff;
document.getElementById("screen").innerHTML = c;
console.log('difference: '+c);
result(c);
}
else {
document.getElementById("screen").innerHTML = "Please press a number first!";
}
}
function result() {
console.log('function result: '+c);
arr1=[]; arr2=[]; item1, item2, op = '';
item1 = c;
console.log('function result new item1: '+item1);
arr1.push(item1);
arr1Function();
}
function del() {
if (arr1!='' && op=='' && arr2=='') {
arr1.pop();
console.log(arr1);
arr1Function();
}
else if (arr1!='' && op!='' && arr2=='') {
op = '';
document.getElementById("screen").innerHTML = op;
}
else if (arr1!='' && op!='' && arr2!='') {
arr2.pop();
console.log(arr2);
arr2Function();
}
}
function clr() {
arr1=[]; arr2=[]; item1,item2,op='';
console.log(arr1+', '+op+', '+arr2+', '+item1+', '+item2);
document.getElementById("screen").innerHTML = '';
document.getElementById("items").innerHTML = '';
}
function arr1Function() {
document.getElementById("screen").innerHTML = arr1;
text = ""; arr1.forEach(myFunction); text += "";
function myFunction(value) {
text += value;
x = parseInt(text);
document.getElementById("screen").innerHTML = x;
item1 = x;
console.log("Arr 1 Parse: "+x);
console.log("Arr 1: "+arr1);
console.log("Item 1: "+item1);
}
}
function arr2Function() {
document.getElementById("screen").innerHTML = arr2;
text = ""; arr2.forEach(myFunction); text += "";
function myFunction(value) {
text += value;
x = parseInt(text);
document.getElementById("screen").innerHTML = x;
item2 = x;
console.log("Arr 2 Parse: "+x);
console.log("Arr 2: "+arr2);
console.log("Item 2: "+item2);
}
}
//css
body {
background-color: orange;
}
.outer-container {
position: static;
background-color: black;
margin: auto;
border: solid black 2px;
width: 350px;
padding: 20px;
box-sizing: border-box;
border-radius: 20px;
}
.items {
background-color: silver;
border: solid white 1px;
display: inline-block;
color: black;
max-width: 100%;
font-size: 16px;
height: 20px;
box-sizing: border-box;
}
.calc-screen {
padding: 10px;
border: solid white 1px;
max-width: 100%;
width: 100%;
height: 50px;
background-color: silver;
color: white;
font-size: 25px;
box-sizing: border-box;
overflow-x: auto;
}
.keys-container {
margin-top: 20px;
width: 100%;
border: solid white 1px;
max-width: 100%;
display: inline-block;
}
#equals {
width: 100%;
}
.keys {
float: left;
border: solid black 1px;
box-sizing: border-box;
width: 25%;
height: 40px;
box-sizing: border-box;
text-align: center;
margin: auto;
font-size: 25px;
padding: 5px;
}
.keys:hover {
background-color: blue;
color: white;
}

update bar chart with drop down menu

I am trying to change the value of xmlURL based on my drop down menu. When the value is passed down on I want to reload my bar chart. Any tips?
google.load('visualization', '1', {
packages: ['corechart', 'bar']
});
google.setOnLoadCallback(drawStacked);
var identified_cash_flows = 0;
var Unidentified_transaction = 0;
var Unidentified_transaction, _within_overall_threshold = 0;
var Identified_counterparty, _unidentified_transaction, _above_threshold = 0;
var Identified_counterparty, _unidentified_transaction, _within_overall_threshold = 0;
var Identified_counterparty, _unidentified_amount, _above_threshold = 0;
var Identified_counterparty, _unidentified_amount, _within_overall_threshold = 0;
var Identified_transaction, _frequency_limit = 0;
var Identified_transaction, _above_cumulative_threshold = 0;
var Identified_transaction, _unidentified_type = 0;
var Identified_transaction = 0;
var counts = {};
var xmlURL = "https://connect.compliancewise.nl/compliancewise/sheetViewExportXML.action?metaData.siteID=242&metaData.sheetId=3832&metaData.sheetViewID=26050&metaData.isheetExportType=xml";
var xmlURL2 = "https://connect.compliancewise.nl/compliancewise/sheetViewExportXML.action?metaData.siteID=242&metaData.sheetId=3832&metaData.sheetViewID=25667&metaData.isheetExportType=xml";
var xml;
var urlie;
var selectUrl;
window.onload = function() {
selectUrl = document.getElementById('selectYear');
}
function changeHiddenInput(objDropDown) {
console.log(objDropDown);
var objHidden = document.getElementById("hiddenInput");
objHidden.value = objDropDown.value;
urlie = objHidden.value;
result.innerHTML = urlie || "";
}
$j.ajax({
url: xmlUrl,
dataType: "xml",
beforeSend: function() {
$j('#loader').hide();
},
success: function(data) {
xml = data;
$j('#loader').hide();
createBarchart();
}
});
<td colspan="2" rowspan="2" style="height: 300px;">
<select id="selectYear" onchange="changeHiddenInput(this)">
<option selected="selected" value="https://connect.compliancewise.nl/compliancewise/sheetViewExportXML.action?metaData.siteID=242&metaData.sheetId=3832&metaData.sheetViewID=26050&metaData.isheetExportType=xml">2016</option>
<option value="https://connect.compliancewise.nl/compliancewise/sheetViewExportXML.action?metaData.siteID=242&metaData.sheetId=3832&metaData.sheetViewID=25667&metaData.isheetExportType=xml">2017</option>
</select>
<input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
<script type="text/javascript" src="https://www.google.com/jsapi?autoload= {'modules':[{'name':'visualization','version':'1.1','packages':['corechart', 'bar']}]}"></script>
<div style="border: 0px solid rgb(201, 0, 1); overflow: hidden; margin: 15px auto; max-width: 100%;">
I know I am using old library loader code but that is for reasons.
There are two undefined values of drawStacked and result

How to show first youtube video in iframe and other in thumbnail?

Hi I want to show only the first video in iframe while other in thumbnail.
Here is my code you can run it on localhost.If you have any solution then please reply me.
index.php file
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title>youtube Channel Videos</title>
<style>
body{
background: #f4f4f4;
font-family: "Arial" sans-serif;
font-size: 14px;
color: #666;
}
#container{
width: 800px;
overflow: auto;
margin: auto;
background: #fff;
padding: 15px;
}
.anc{
padding: 2px 6px;
background: #EFF7FF;
color: #069;
border: 1px solid #C2D9EF;
margin: 0px 0px 0px 5px;
-moz-border-radius: 1px;
-webkit-border-radius: 1px;
text-decoration: none;
text-align: center;
}
</style>
<!-- <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">-->
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="http://www.youtube.com/player_api"></script>
<!-- <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>-->
<script src="js/script.js"></script>
</head>
<body>
<?php
// put your code here
?>
<div id="container">
<h1>Youtube Videos</h1>
<ul id="results">
</ul>
<div id="page" style="padding-top: 15px;padding-left: 42px;"></div>
</div>
<script>
players = new Array();
//alert($("iframe.yt_players"));
function onYouTubeIframeAPIReady() {
var temp = $("iframe.yt_players");
for (var i = 0; i < temp.length; i++) {
var t = new YT.Player($(temp[i]).attr('id'), {
events: {
'onStateChange': onPlayerStateChange
}
});
players.push(t);
}
}
window.onload = setTimeout(onYouTubeIframeAPIReady, 10000);
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
var temp = event.target.a.src;
var tempPlayers = $("iframe.yt_players");
for (var i = 0; i < players.length; i++) {
if (players[i].a.src != temp) players[i].stopVideo();
}
}
}
</script>
</body>
</html>
script.js file
function tplawesome(template, data) {
// initiate the result to the basic template
res = template;
// for each data key, replace the content of the brackets with the data
for(var i = 0; i < data.length; i++) {
res = res.replace(/\{\{(.*?)\}\}/g, function(match, j) { // some magic regex
return data[i][j];
});
}
return res;
}
var channelName= "TechGuyWeb";
$(document).ready(function(){
$.get("https://www.googleapis.com/youtube/v3/channels",{
part: 'contentDetails',
forUsername: channelName,
key:'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'},
function(data){
console.log(data);
$.each(data.items,function(i, item){
var pid = item.contentDetails.relatedPlaylists.uploads;
//console.log(pid);
getVids(pid);
});
}
);
//var pid="10thStreetPreschool";
// function getvids(pid){
// $.get("https://www.googleapis.com/youtube/v3/playlistItems",{
// part: 'snippet',
// maxResults: 10,
// playlistId:pid,
// key:'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'},
// function(data){
// var output;
// $.each(data.items,function(i, item){
// console.log(data);
// var v_id = item.snippet.resourceId.videoId;
// //alert(item.snippet.resourceId.videoId);
// //var video_title = item.snippet.title;
// //output= '<li>'+video_title+'</li>';
// $.get("item.html",function(data){
// $('#results').append(tplawesome(data, [{"title":item.snippet.title,"videoid":item.snippet.resourceId.videoId,"description":item.snippet.description}]));
// getcount(v_id);
// });
// //$('#results').append(output);
// });
// }
// );
// }
function getVids(pid, pageToken){
var data = {
part: 'snippet',
maxResults: 10,
playlistId: pid,
key: 'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'
}
try{
if(pageToken){
data["pageToken"] = pageToken;
}
}catch(err){
}
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", data,
function(data){
var output;
$('#results').html("");
$.each(data.items,function(i, item){
console.log(data);
var v_id = item.snippet.resourceId.videoId;
// var total_results =data.pageInfo.totalResults;
// console.log(total_results);
$.get("item.html",function(data){
$('#results').append(tplawesome(data, [{"title":item.snippet.title,"videoid":item.snippet.resourceId.videoId,"description":item.snippet.description}]));
getcount(v_id);
});
//$('#results').append(output);
});
$('#page').html("");
try{
if(data.prevPageToken){
$("#page").append('<span><a class="anc" href="javascript:void(0);" onclick="getVids(\'' + pid + '\', \'' + data.prevPageToken + '\');">« Previous<a/></span>');
}
}catch(err){
}
try{
if(data.nextPageToken){
$("#page").append('<span><a class="anc" href="javascript:void(0);" onclick="getVids(\'' + pid + '\', \'' + data.nextPageToken + '\');">Next »<a/></span>');
}
}catch(err){
}
});
}
function getcount(v_id){
$.get("https://www.googleapis.com/youtube/v3/videos",{
part: 'statistics',
id: v_id,
key:'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'},
function(data){
$.each(data.items,function(i, item){
var views = item.statistics.viewCount;
//console.log(views);
$('#'+v_id).append(views);
});
}
);
}
});
function getVids(pid, pageToken){
var data = {
part: 'snippet',
maxResults: 10,
playlistId: pid,
key: 'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'
}
try{
if(pageToken){
data["pageToken"] = pageToken;
}
}catch(err){
}
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", data,
function(data){
var output;
$('#results').html("");
$.each(data.items,function(i, item){
console.log(data);
var v_id = item.snippet.resourceId.videoId;
//alert(item.snippet.resourceId.videoId);
//var video_title = item.snippet.title;
//output= '<li>'+video_title+'</li>';
$.get("item.html",function(data){
$('#results').append(tplawesome(data, [{"title":item.snippet.title,"videoid":item.snippet.resourceId.videoId,"description":item.snippet.description}]));
getcount(v_id);
});
//$('#results').append(output);
});
$('#page').html("");
try{
if(data.prevPageToken){
$("#page").append('<span><a class="anc" href="javascript:void(0);" onclick="getVids(\'' + pid + '\', \'' + data.prevPageToken + '\');">« Previous<a/></span>');
}
}catch(err){
}
try{
if(data.nextPageToken){
$("#page").append('<span><a class="anc" href="javascript:void(0);" onclick="getVids(\'' + pid + '\', \'' + data.nextPageToken + '\');">Next »<a/></span>');
}
}catch(err){
}
});
}
function getcount(v_id){
$.get("https://www.googleapis.com/youtube/v3/videos",{
part: 'statistics',
id: v_id,
key:'AIzaSyBX94DoCYdtIwALVPfqSVar6izj3wCJ1M4'},
function(data){
$.each(data.items,function(i, item){
var views = item.statistics.viewCount;
console.log(views);
$('#'+v_id).append(views);
});
}
);
}
item.html file
<div class="item" style="padding-bottom: 30px;">
<iframe id="player{{videoid}}" class="yt_players" src="http://www.youtube.com/embed/{{videoid}}?rel=0&enablejsapi=1;showinfo=0;&wmode=Opaque" width="560" height="315" frameborder="0" allowfullscreen></iframe>
<div style="margin-bottom: -22px;margin-top: -20px;"><h2 style="font-size:18px;">{{title}}</h2></div>
<div style="margin-bottom: -18px;"><h5 style="font-size:16px;">{{description}}</h5> </div>
<div><h5 style="font-size:14px;margin-top: -5px;">Total Views: <span id="{{videoid}}"></span></h5> </div>
</div>

Passing array of dates to Javascript sort

I'm having problem with javascript sort function. I have this function:
var compare = function(a, b) {
if(a.last_nom < b.last_nom) {
return -1;
}
if(a.last_nom > b.last_nom) {
return 1;
}
return 0;
}
And the I call it with:
var sortedData = fullData.sort(compare);
But I don't know how to pass dates correctly.
You can find jsbin example here
Thank you in advance
As requested, to make sense of my code here is full code:
<html lang="en-US">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css">
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.0/sweetalert.min.css" rel="stylesheet">
<link rel="icon" href="http://www.mzirafos.lt/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.mzirafos.lt/favicon.ico" type="image/x-icon" />
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mėmelio Žirafos - Facebook feeds page</title>
<style>
html {
overflow-y: scroll;
}
header {
margin-bottom: 50px;
}
.progress {
top: 50%;
width: 50%;
margin: 0 auto;
}
.event-only .not-event {
display: none;
}
.post-by {
display: block;
margin-bottom: 25px;
}
.post-date {
display: block;
}
.card .card-content .card-title {
line-height: 26px;
margin-bottom: 15px;
display: inline-block;
}
img.responsive-img {
width: 100%;
}
</style>
</head>
<body>
<div class="progress">
<div class="indeterminate"></div>
</div>
<div class="hide" id="content">
<!--header-->
<header>
<nav class="top-nav">
<div class="container">
<div class="nav-wrapper">
<p>Mėmelio Žirafos Facebook feeds page</p>
</div>
</div>
</nav>
</header>
<!--end header-->
<div class="container">
<div class="row">
<!--checkbox to show all posts or events only-->
<div class="col s6">
<p>
<input type="checkbox" id="events-only" />
<label for="events-only">Show events only</label>
</p>
</div>
<!--end checkbox-->
</div>
<div class="row">
<h3 class="center-align" id="posts-acc-title">Facebook posts</h3>
<!--posts wrapper-->
<div class="col s12" id="fb-posts-wrap"></div>
<!--end posts wrapper-->
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sugar/1.4.1/sugar.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.0/sweetalert.min.js"></script>
<script src="https://cdn.rawgit.com/zenorocha/clipboard.js/master/dist/clipboard.min.js"></script>
<script>
(function() {
/*
* Our Globals
*/
var html = '';
var finalData = [];
var token = 'CAAQYWWjo5zkBAGlqs2AxxsWKcgWEI0VM3UA7555dhCQEOCTu9VW91tpfaNvrt4tS0w8DkxPJHvRENRrMeDT9QC1aSvHdZA7nhw9ZBqZAyUhMM6PTQoJggn7pJRHEO8xQJp8lsGZAqixVU8SvrMlhUUhwmzB11h9ISqd3MvmoD4aVZBPPD1geO';
var baseURL =
'https://graph.facebook.com/v2.4/{slug}/feed?fields=picture,created_time,message,link,type,description,caption,full_picture,id,admin_creator,from&limit=50&access_token={token}';
var slugs = [{
slug: 'sisaidgallery',
complete: false
}, {
slug: 'duzenos',
complete: false
}, {
slug: 'bbcnews',
complete: false
}, {
slug: 'Klaipeda.renginiai',
complete: false
}, {
slug: 'PORTbyBarBara',
complete: false
}, {
slug: 'Kastonas',
complete: false
}, {
slug: 'klaipedosdramosteatras',
complete: false
}, {
slug: '238899589464193',
complete: false
}];
/*
* allComplete
*/
var allComplete = function() {
for (var i = 0; i < slugs.length; i++) {
if (slugs[i].complete === false) {
return false;
}
}
return true;
};
/*
* makeURL
*/
var makeURL = function(url, token, slug) {
return url.replace('{token}', token).replace('{slug}', slug);
};
/*
* Date formatter
*/
var dateFormatter = function(date) {
var dateFormat = '{HH}:{mm}, {Weekday}, {d} {Month}, {yyyy}';
return Date.create(date).format(dateFormat);
}
/*
* Mark slug as complete
*/
var completeSlug = function(mySlug) {
for (var i in slugs) {
if (slugs[i].slug === mySlug) {
slugs[i].complete = true;
}
}
};
var copyTextID = 100;
/*
* template
*/
var template = '' +
'<div class="card blue-grey darken-1 hoverable {isEvent}">' +
'<div class="card-content white-text">' +
'<span class="post-date">Posted on: {fb-post-date}</span>' +
'<span class="post-by">Post by: {fb-post-from}</span>' +
'<div class="row">' +
'<div class="col s2">' +
'<img class="responsive-img" src="{fb-image}" alt=""/>' +
'</div>' +
'<div class="col s10" id="post-target-{fb-post-id}">' +
'<span class="card-title">{fb-post-title}</span>' +
'<p>{fb-post-text}</p>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="card-action">' +
'<a target="_blank" href="{fb-post-link}">Open post</a>' +
'<a class="waves-effect waves-light btn white-text red darken-1 hoverable" data-clipboard-target="#post-target-{fb-post-id}"><i class="material-icons right">subject</i>Copy</a>' +
'</div>' +
'</div>';
/*
* checking title, text and images
*/
var replaceUndefined = function(str) {
return str === undefined ? '' : str;
};
var replaceImage = function(str) {
return str === undefined ? 'https://placehold.it/350x150' : str;
};
/*
* bindTemplate
*/
var bindTemplate = function(template, obj) {
return template
.replace('{isEvent}', obj.type === 'event' ? '' : 'not-event')
.replace('{fb-image}', replaceImage(obj.picture))
.replace('{fb-post-from}', obj.from.name)
.replace('{fb-post-title}', replaceUndefined(obj.description))
.replace('{fb-post-text}', replaceUndefined(obj.message))
.replace('{fb-post-link}', obj.link)
.replace('{fb-post-date}', dateFormatter(obj.created_time))
.replace(/{fb-post-id}/g, obj.id);
};
var makeAjax = function(fbUrl, next, slug) {
$.ajax({
url: fbUrl
}).done(function(data) {
next(data, slug);
});
};
/*
* renderTemplate
*/
var renderTemplate = function() {
$('#fb-posts-wrap').html(html);
};
/*
* makeAjaxCalls
*/
var makeAjaxCalls = function(slugs) {
slugs.forEach(function(slug) {
makeAjax(makeURL(baseURL, token, slug.slug), showAllPosts, slug.slug);
});
};
/*
* Flatten data
*/
var flattenData = function(data) {
var fullData = [];
var empty = [];
data.forEach(function(row) {
fullData.push(row.data);
});
return empty.concat.apply(empty, fullData);
};
var compare = function(a, b) {
if (a.last_nom < b.last_nom) {
return -1;
}
if (a.last_nom > b.last_nom) {
return 1;
}
return 0;
}
var showAllPosts = function(data, slug) {
// Let's first mark this slug as complete
completeSlug(slug);
// And store our data
finalData.push(data);
if (allComplete()) {
// merge all data
var fullData = flattenData(finalData);
// sort all data and
var sortedData = fullData.sort(compare);
// build the html
sortedData.forEach(function(obj) {
html += bindTemplate(template, obj);
});
// call the renderTemplateFunction
renderTemplate();
// finally hide the progress bar
$('.progress').fadeOut();
$('#content').removeClass('hide');
}
};
/*
* Listen to the change in the checkbox
*/
$('#events-only').change(function() {
if ($(this).is(':checked')) {
// hide the non events with css
$('#fb-posts-wrap').addClass('event-only');
} else {
// show the non events with css
$('#fb-posts-wrap').removeClass('event-only');
}
});
/*
* Kick off
*/
makeAjaxCalls(slugs);
})();
</script>
</body>
</html>
What is last_nom? There is no such function in JS Date specification
Try this:
function compare(a, b) {
if (a.getTime() > b.getTime())
return 1;
if (a.getTime() < b.getTime())
return -1;
return 0
}
var sortedDatesArray = unsortedDatesArray.sort(compare);

Categories