i want to display this small digits into this code - javascript

I want to display result with small digits.
The result of code is ATRILCXPRICBTC 1.134916286172e-7 1.311458819577e-7 and I want to make is look like 0.00000001.
async function init() {
const url = "https://exchange-api.lcx.com/market/tickers";
const resp = await fetch(url);
const json = await resp.json();
const LCXUSDCBid = json.data['LCX/USDC'].bestBid
const BTCUSDCAsk = json.data['BTC/USDC'].bestAsk
const BTCUSDCBid = json.data['BTC/USDC'].bestBid
const ATRILCXBid = json.data['ATRI/LCX'].bestBid
const ATRILCXAsk = json.data['ATRI/LCX'].bestAsk
const ATRILCXPRICUSDCEBid = LCXUSDCBid * ATRILCXBid
const ATRILCXPRICUSDCEAsk = LCXUSDCBid * ATRILCXAsk
const ATRILCXPRICBTCBid = ATRILCXPRICUSDCEBid / BTCUSDCBid
const ATRILCXPRICBTCAsk = ATRILCXPRICUSDCEAsk / BTCUSDCBid
const tableBody = document.querySelector("#prices tbody");
tableBody.innerHTML += `<tr>
<td style="color:blue;">ATRILCXPRICBTC</td>
<td style="color:green;">${ATRILCXPRICBTCBid}</td>
<td style="color:red;">${ATRILCXPRICBTCAsk}</td>
</tr>`;
}
init();
This is what I tried but it didn't work.
I want to set to all file

You're looking for Number.toFixed().
x = 0.0000000005;
console.log(x); // 5e-10
console.log(x.toFixed(10)); // 0.0000000005

Related

Javascript and Google Sheet - Display only one element of array

I'm learning javascript, hence my question might be a bit silly/simple.
Following a tutorial on Udemy, I was able to display a spreadsheet from Google Sheet in my website, using javascript to retrieve all rows contained in the document and pass them to a container in an HTML page.
This is great.
Now I would like to visualise only one row at a time, at a specific interval.
After some search I realised I can do this by using getElementById in conjunction with .innerHTML within a loop but I can't figure out what I am supposed to pass and where.
So, here is the HTML I'm using
<!DOCTYPE html>
<html><head><title>Testing Data from Sheets</title></head>
<body>
<div class="output"></div>
<script src="sheets.js"></script>
</body>
</html>
And here is the JS
const sheetID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const base = `https://docs.google.com/spreadsheets/d/${sheetID}/gviz/tq?`;
const sheetName = 'quotes';
let qu = 'Select D';
const query = encodeURIComponent(qu);
const url = `${base}&sheet=${sheetName}&tq=${query}`;
const data = [];
document.addEventListener('DOMContentLoaded', init);
const output = document.querySelector('.output');
function init() {
console.log('ready');
fetch(url)
.then(res => res.text())
.then(rep => {
//console.log(rep);
const jsData = JSON.parse(rep.substr(47).slice(0, -2));
console.log(jsData);
const colz = [];
jsData.table.cols.forEach((heading) => {
if (heading.label) {
colz.push(heading.label.toLowerCase().replace(/\s/g, ''));
}
})
jsData.table.rows.forEach((main) => {
//console.log(main);
const row = {};
colz.forEach((ele, ind) => {
//console.log(ele);
row[ele] = (main.c[ind] != null) ? main.c[ind].v : '';
})
data.push(row);
})
maker(data);
})
}
function maker(json) {
const div = document.createElement('div');
div.style.display = 'grid';
output.append(div);
let first = true;
json.forEach((el) => {
//console.log(ele);
const keys = Object.keys(el);
div.style.gridTemplateColumns = `repeat (${keys.length} ,'1fr')`;
if (first) {
first = false;
keys.forEach((heading) => {
const ele = document.createElement('div');
//ele.textContent = heading.toLocaleUpperCase();
ele.style.background = 'black';
ele.style.color = 'white';
ele.style.fontFamily = 'Helvetica';
div.append(ele);
})
}
keys.forEach((key) => {
const ele = document.createElement('div');
//ele.style.border = '1px solid #ddd';
ele.textContent = el[key];
ele.style.background = 'black';
ele.style.color = 'white';
ele.style.fontFamily = 'Helvetica';
div.append(ele);
})
console.log(keys);
})
}
Thanks heaps for helping!
I tried using the following from other messages I've found on the forum:
var i = 0; // the index of the current item to show
setInterval(function() { // setInterval makes it run repeatedly
document
.getElementById('output')
.innerHTML = jsData[i++];
if (i == jsData.length) i = 0;
}, 1000);

How can I add a row to my html document for every player including their stats?

The code currently takes from a .log I have, and grabs the username of players in my lobby and returns stats (# of wins, level, etc.) of the player onto an electron HTML page in a table.
Currently, it only shows one row, with only one players' stats included in the row. I am trying to make it so that each player will show up in stacking rows.
Picture of what the html electron window shows
I also want the rows to update every time "checkforupdates" is ran but I figured I should stick to one issue at a time.
const { app, BrowserWindow } = require('electron');
const fs = require('fs');
const prompt = require('prompt-sync')();
const Hypixel = require('hypixel-api-reborn');
const hypixel = new Hypixel.Client('77684239-5a07-4ea4-bc9c-2f07db9fddb7');
const filePath = 'C:/Users/****/AppData/Roaming/.minecraft/logs/blclient/minecraft/latest.log';
const keyword = 'ONLINE: ';
let lastTrimmed = '';
console.clear();
let win;
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('playerstats.html');
}
app.whenReady().then(createWindow);
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
app.on('ready', async () => {
const checkForUpdates = () => {
fs.promises.readFile(filePath, 'utf8')
.then(data => {
if (data.includes(keyword)) {
const index = data.lastIndexOf(keyword);
const line = data.substring(index);
const parts = line.split('\n');
const trimmed = parts[0].trim();
if (trimmed !== lastTrimmed) {
const names = trimmed.split(', ');
names.forEach(async name => {
const playerName = name.replace(keyword, '');
try {
const player = await hypixel.getPlayer(playerName);
const winstreak = player.stats.bedwars.winstreak || '?';
const finalKills = player.stats.bedwars.finalKills;
const fkdr = player.stats.bedwars.finalKDRatio;
const wins = player.stats.bedwars.wins;
const lvl = player.stats.bedwars.level;
win.webContents.executeJavaScript(`
document.getElementById("IGN").innerHTML = "${player}";
document.getElementById("wins").innerHTML = "${wins}";
document.getElementById("finalKills").innerHTML = "${finalKills}";
`);
console.log(`(${lvl})${playerName}: ws - ${winstreak} fkdr - ${fkdr} finals - ${finalKills} wins - ${wins}`);
} catch (err) {
console.error(`${playerName} Is Nicked`);
}
});
lastTrimmed = trimmed;
}
}
})
.catch(console.error);
};
setInterval(checkForUpdates, 1000);
});
<!DOCTYPE html>
<html>
<head>
<title>Player Stats</title>
</head>
<body>
<table>
<tr>
<th>IGN</th>
<th>Wins</th>
<th>Finals</th>
<th>FKDR</th>
</tr>
<tr>
<td id="IGN"></td>
<td id="wins"></td>
<td id="finalKills"></td>
<td id="fkdr"></td>
</tr>
</table>
<script>
const playerData = window.playerData;
document.querySelector("#IGN").textContent = playerData.player;
document.querySelector("#wins").textContent = playerData.wins;
document.querySelector("#final-kills").textContent = playerData.finalKills;
</script>
</body>
</html>
I tried looking at other forums regarding them, but every other user had more complex programs that integrated adding rows, and I couldn't figure out how to implement it into my code.
The forums i found on stackoverflow that were relevant to me only asked about a singular row.
I also thought about just adding 15 more table rows (I only need 16 rows max) but I couldn't figure out how to divert the "getElementById()" to fill out data in a different row.
I'm not sure I understood your problem, but, if you have an array of players, you could do something like:
<script>
for(let i = 0; i < players.lenght; i++) {
let table = document.getElementById("tableId")
let newTr = document.createElement("tr")
let td1 = document.createElement("td")
td1.innerText = players[i].player
let td2 = document.createElement("td")
td2.innerText = players[i].wins
let td3 = document.createElement("td")
td3.innerText = players[i].finalKills
tr.append(td1)
tr.append(td2)
tr.append(td3)
table.append(tr)
}
</script>
This script cycles trough an array of players and for each one of them creates a row in the table with the relative tds.
Notice that you need to give the table an id (tableId in my example) also notice that you could use thead and tbody tags.

Trying to add two value and insert them in HTML as a paragraph

I'm currently trying to make this code work properly.
I think the problem is within the two last line of my code, but I don't understand why it doesn't work. Can't I add those two value and just insert the result in my HTML ?
const option1=document.getElementById("checkbox1")
const option2=document.getElementById("checkbox2")
const option3=document.getElementById("checkbox3")
let priceFirstMonth = 19.95;
let priceAnnual = 29.95;
const setPriceMonth = document.querySelector(".firstMonthPrice");
const calculatedPrice = () => {
/* calculate the amount of all options */
let addedOptionsPrice;
if (option1.checked) {
addedOptionsPrice = addedOptionsPrice+10;
}
if (option2.checked) {
addedOptionsPrice = addedOptionsPrice+5;
}
if (option3.checked) {
addedOptionsPrice = addedOptionsPrice+10;
}
/* add the amount to regular prices*/
priceFirstMonth = document.createElement('p');
priceAnnual = document.createElement('p');
priceFirstMonth.innerHTML = priceFirstMonth + addedOptionsPrice;
priceAnnual.innerHTML = priceAnnual + addedOptionsPrice;
setPriceMonth.appendChild(priceFirstMonth);
}
Thanks in advance for any help or explication on my behavior !
Just rename your variables.
const priceFirstMonthElement = document.createElement('p');
const priceAnnualElement = document.createElement('p');
priceFirstMonthElement.innerHTML = priceFirstMonth + addedOptionsPrice;
priceAnnualElement.innerHTML = priceAnnual + addedOptionsPrice;
setPriceMonth.appendChild(priceFirstMonthElement);
You are just assigning the element to the same variable that is for calculation.
priceFirstMonth = document.createElement('p');
priceAnnual = document.createElement('p');
priceFirstMonth = priceFirstMonth + addedOptionsPrice;
priceAnnual = priceAnnual + addedOptionsPrice;
setPriceMonth.innerHTML=priceFirstMonth;
A cleaner version of your code:
const checkboxElement1 = document.querySelector("#checkbox1");
const checkboxElement2 = document.querySelector("#checkbox2");
const checkboxElement3 = document.querySelector("#checkbox3");
const firstMonthPriceElement = document.querySelector(".firstMonthPrice");
const checkboxElements = document.querySelectorAll(".checkbox");
let basePriceFirstMonth = 19.95;
let basePriceAnnual = 29.95;
let optionalPrice;
/* calculate the amount of all options */
const priceCalculation = () => {
if (option1.checked) {
optionalPrice = optionalPrice + 10;
}
if (option2.checked) {
optionalPrice = optionalPrice + 5;
}
if (option3.checked) {
optionalPrice = optionalPrice + 10;
}
}
checkboxElements.forEach(checkbox => {
checkbox.addEventListener("click", () => {
priceCalculation();
});
});
/* add the amount to regular prices*/
priceFirstMonthElement = document.createElement('p');
priceAnnualElement = document.createElement('p');
priceFirstMonthElement.innerHTML = basePriceFirstMonth + optionalPrice;
priceAnnualElement.innerHTML = basePriceAnnual + optionalPrice;
firstMonthPriceElement?.appendChild(priceFirstMonthElement);

API Images not displaying and cards not dynamically populated

I am trying to display Unsplash images on cards.
The cards are created using JavaScript.
The 10 objects from the Unsplash API is shown on the console.
However, I cannot seem to find the problem on why the cards and the API Unsplash images are not displaying.
Appreciate any help, thanks.
const resultsNav = document.getElementById('resultsNav');
const favouritesNav = document.getElementById('favouritesNav');
const imagesContainer = document.querySelector('.images-container');
const saveConfirmed = document.querySelector('.saveConfirmed');
const loader = document.querySelector('.loader');
// Unsplash API
const count = 10;
const apiKey = 'DEMO KEY';
const apiUrl = `https://api.unsplash.com/photos/random?client_id=${apiKey}&count=${count}`;
let resultsArray = [];
function updateDOM() {
resultsArray.foreach((result) => {
// Card Container
const card = document.createElement('div');
card.classList.add('card');
// link
const link = document.createElement('a');
link.href = result.hdurl;
//Images
const image = document.createElement('img');
image.src = result.url;
image.alt = 'Image';
image.loading = 'lazy';
image.classList.add('card-img-top');
//Card Body
const cardBody = document.createElement('div');
cardBody.classList.add('card-body');
// Save Text
const saveText = document.createElement('p');
saveText.classList.add('clickable');
saveText.textContent = 'Add To Favourites';
// Append
cardBody.append(saveText);
link.appendChild(image);
card.append(link, cardBody);
imagesContainer.appendChild(card);
});
}
// Get 10 Images from Unsplash API
async function getUnplashPictures() {
try {
const response = await fetch(apiUrl);
resultsArray = await response.json();
console.log(resultsArray);
updateDOM();
} catch (error) {
// Catch Error Here
}
}
// On Load
getUnplashPictures();
Let's fix the for loop part;
foreach() usage should be with capital E as .forEach() that cause an error and your response objects prop were different named.
let resultsArray = [];
function updateDOM() {
for (let result of resultsArray) {
// Card Container
const card = document.createElement('div');
card.classList.add('card');
// link
const link = document.createElement('a');
link.href = result.links.self;
//Images
const image = document.createElement('img');
image.src = result.urls.small;
image.alt = 'Image';
image.loading = 'lazy';
image.classList.add('card-img-top');
//Card Body
const cardBody = document.createElement('div');
cardBody.classList.add('card-body');
// Save Text
const saveText = document.createElement('p');
saveText.classList.add('clickable');
saveText.textContent = 'Add To Favourites';
// Append
cardBody.append(saveText);
link.appendChild(image);
card.append(link, cardBody);
imagesContainer.appendChild(card);
};
}

A function doesn't respond in ref.on() even if the result is correct

I have been trying to create an app named workspace. I had asked another question earlier but now the features I have added are more. There is a remarks system. I have tried using different versions of my code and the code I have given has the best version I created. I cannot find an answer to my question on the net so I had to ask it here.
var ref = firebase.database().ref();
function stdRemarks(studentName){
let finalStuff;
ref.on("value", function(snapshot){
let keys = Object.keys(snapshot.val().schools[returnCurrentUser()][studentName]['remarks']);
for(i=0;i<keys.length;i++){
let objectToDealWith = snapshot.val().schools[returnCurrentUser()][studentName]['remarks'];
let remark = objectToDealWith[keys[i]]['remark'];
let examiner = objectToDealWith[keys[i]]['examiner'];
let fullRemark = ` ${examiner}: ${remark} | `
finalStuff += fullRemark;
}
return finalStuff;
});
}
ref.on("value", function(snapshot){
let dashTab = document.getElementById("dashboard_table");
let btn = document.getElementById("csv_blob");
let btn2 = document.getElementById("json_view");
let btn3 = document.getElementById("json_export");
btn.style.display = "block";
btn2.style.display = "block";
$("#json_export").css('display', 'block');
dashTab.innerHTML = "<thead><tr><th>Student Name</th><th>Class</th><th>Email</th><th>Subject</th><th>Project Info</th><th>Remarks</th><th>Project</th><th style='display: none;'>Project Download URL</th><th>Add Remark</th></tr></thead>";
let jsonRecieved = snapshot.val();
let objectToDealWith = snapshot.val().schools[returnCurrentUser()];
let lengthOfIt = Object.size(objectToDealWith);
for(i=0;i<lengthOfIt;i++){
let int = i + 1;
let names = Object.keys(objectToDealWith);
let stdName = names[i];
let finalResult = objectToDealWith[stdName];
document.getElementById("schoolnameis").innerText = "Dashboard - " + objectToDealWith['i'];
let stdClass = finalResult['class'];
let stdEmail = finalResult['email'];
let stdSubject = finalResult['subject'];
let stdiName = finalResult['stdname'];
let stdProjectName = finalResult['projectname']
let stdProjectInfo = finalResult['projectinfo'];
let stdProjectLink = finalResult['projectlink'];
console.log(stdRemarks(stdiName))
let elementToPush = `<tr><td>${stdiName.replace(/undefined/g, '')}</td><td>${stdClass.replace(/undefined/g, '')}</td><td>${stdEmail.replace(/undefined/g, '')}</td><td>${stdSubject.replace(/undefined/g, '')}</td><td>${stdProjectInfo.replace(/undefined/g, '')}</td><td>${stdRemarks(stdnameName).replace(/undefined/g, '')}</td><td><a href=${stdProjectLink}>${stdProjectName.replace(/undefined/g, '')}</a></td><td style='display:none;'>${stdProjectLink}</td><td id="${stdName}" style='text-align:center;' onclick="closeThatSomeThing();getIdOfTd(this.id)">&#x2795</td></tr>`;
dashTab.innerHTML += elementToPush;
}
});
So everything is working fine but some stuff here seems to corrupt the whole code. My database looks somewhat like this
Here is the error.
//A warning by firebase.
#firebase/database: FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot read property 'replace' of undefined
//An error occuring on the variable `elementToPush` and its part ${stdRemarks(stdnameName).replace(/undefined/g, '') in the code.
Cannot read property 'replace' of undefined
I have to submit this project tomorrow.
your function 'stdRemarks' has a return type of 'void'. either return the the complete ref.on() or move 'finalstuff' outside the .on() function call and make sure the function 'stdRemarks' has the desired return type. in this case this would be a 'string';
function stdRemarks(studentName){
let finalStuff = "";
ref.on("value", function(snapshot){
let keys = Object.keys(snapshot.val().schools[returnCurrentUser()][studentName]['remarks']);
for(i=0;i<keys.length;i++){
let objectToDealWith = snapshot.val().schools[returnCurrentUser()][studentName]['remarks'];
let remark = objectToDealWith[keys[i]]['remark'];
let examiner = objectToDealWith[keys[i]]['examiner'];
let fullRemark = ` ${examiner}: ${remark} | `
finalStuff += fullRemark;
}
});
return finalStuff;
}
I made it work by using this code.
ref.on("value", function(snapshot){
let dashTab = document.getElementById("dashboard_table");
let btn = document.getElementById("csv_blob");
let btn2 = document.getElementById("json_view");
let btn3 = document.getElementById("json_export");
btn.style.display = "block";
btn2.style.display = "block";
$("#json_export").css('display', 'block');
dashTab.innerHTML = "<thead><tr><th>Student Name</th><th>Class</th><th>Email</th><th>Subject</th><th>Project Info</th><th>Remarks</th><th>Project</th><th style='display: none;'>Project Download URL</th><th>Add Remark</th></tr></thead>";
let jsonRecieved = snapshot.val();
let objectToDealWith = snapshot.val().schools[returnCurrentUser()];
let lengthOfIt = Object.size(objectToDealWith)-1;
for(i=0;i<lengthOfIt;i++){
let finalRemark;
let int = i + 1;
let names = Object.keys(objectToDealWith);
let stdName = names[i];
let finalResult = objectToDealWith[stdName];
let stdClass = finalResult['class'];
let stdEmail = finalResult['email'];
let stdSubject = finalResult['subject'];
let stdiName = finalResult['stdname'];
for(var e=0;e<Object.size(objectToDealWith[stdName]['remarks']);e++){
let keys = Object.keys(objectToDealWith[stdName]['remarks']);
let remark = objectToDealWith[stdName]['remarks'][keys[e]]['remark'];
let examiner = objectToDealWith[stdName]['remarks'][keys[e]]['examiner'];
let completeRemark = ` | ${examiner} : ${remark} `
finalRemark += completeRemark;
}
let stdProjectName = finalResult['projectname']
let stdProjectInfo = finalResult['projectinfo'];
let stdProjectLink = finalResult['projectlink'];
let elementToPush = `<tr><td>${stdiName}</td><td>${stdClass}</td><td>${stdEmail}</td><td>${stdSubject}</td><td>${stdProjectInfo}</td><td>${finalRemark.replace(/undefined/g, '')}</td><td><a href=${stdProjectLink}>${stdProjectName}</a></td><td style='display:none;'>${stdProjectLink}</td><td id="${stdName}" style='text-align:center;' onclick="closeThatSomeThing();getIdOfTd(this.id)">&#x2795</td></tr>`;
dashTab.innerHTML += elementToPush;
}
});
What i did here was that i turned i to e in the second loop and it worked...

Categories

Resources