How can get totalBalanceAmount value from getSavingsInput() and put into (HERE)? - javascript

How can get totalBalanceAmount value from getSavingsInput() that i can put into (HERE)?
function getSavingsInput() {
let totalBalance = document.getElementById('balance')
let totalBalanceAmount = parseFloat(totalBalance.value)
return totalBalanceAmount;
}
document.getElementById('Savings').addEventListener('click',function() {
let savingInput = getInput('savigns-input') // this is the another function
let savingsInputAmount = parseFloat(savingInput)
const savignsAmount = (HERE) % savingsInputAmount;
const savedAmount = document.getElementById('saved-amount')
savedAmount.innerText = savignsAmount;
})

Related

value of queryselected/getElementByClass returns value as empty

when I try to querySelect an Element from another module, it always returns empty string ? what should do to fix this? the element exists because when i console log it, the element is there, just the value always returns empty even after i have filled the input in UI, its just that when i press submit its returning empty.
furthermore, if i move the code to the scope where the function is being exported, it works
below code is inside the function footerSubmitSection() that is being exported to another module called addNewOrderFormMain.js where all the components is being appended to the main container and exported to the index.js
the console.log returns
// order ID
db.collection('UserDatabase').doc(currentUserID).get().then((doc) => {
function dateForOrder(){
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0');
let yyyy = today.getFullYear();
today = mm+dd+yyyy;
return today
}
let todayOrderNum = db.collection('OrderDatabase').where('OrderDate', '==', `${orderDate}`)
.get()
.then((snapshot) => {
length = snapshot.size + 1;
let salesRepID = doc.data().SaleID
let salesRepName = doc.data().Name
let orderID = salesRepID + dateForOrder()+'-'+ length + "-"+ editversion
console.log(deliveryMethodInput)
if (deliveryMethodInput=== 'Pick Up'){
const pickupLocationInput = document.getElementsByClassName('orderDetailSectionMidPickupLocationSelect')[0].value;
let pickupLocation = pickupLocationInput;
db.collection('OrderDatabase').doc(orderID).set({
PickupLocation:pickupLocation,
ShippingAddress:"",
BusinessName:businessName,
CustomerType:customerType,
BillingAddress:billingAddress,
CustomerPhoneNumber:customerPhoneNum,
DeliveryMethod:deliveryMethod,
ShipOrPickDate:shipOrPickDate,
PaymentMethod:paymentMethod,
Notes:notes,
OrderDate:orderDate,
OrderStatus:orderStatus,
OrderID:orderID,
salesRepID:salesRepID,
salesRepName:salesRepName,
})
db.collection('CustomerDatabase').get().then((snapshot) => {
snapshot.forEach((doc) => {
if(businessNameValue === doc.data().BusinessName){
let customerID = doc.data().CustomerID;
db.collection('OrderDatabase').doc(orderID).update({
CustomerID:customerID,
})
}
})
})
let subtotalArray=[]; /////////////this is the block im having issue with
let sum = 0
const basket = document.getElementsByClassName('orderProductSectionMidItemContainer')
Array.from(basket).forEach((basketItem) => {
const basketItemName = basketItem.getElementsByClassName('orderProductSectionMidDisplayItemNameInput')[0];
const basketItemPrice = basketItem.getElementsByClassName('orderProductSectionMidDisplayPriceInput')[0];
const basketItemQuantity = basketItem.getElementsByClassName('orderProductSectionMidDisplayQuantitiyInput')[0];
const basketItemDiscount = basketItem.getElementsByClassName('orderProductSectionMidDisplayDiscountInput')[0];
const basketItemSubtotal = basketItem.getElementsByClassName('orderProductSectionMidDisplaySubtotal')[0];
subtotalArray.push(basketItemSubtotal.value);
console.log(basketItemName.value)
console.log(basketItemName.value)
console.log(basketItemPrice.value)
console.log(basketItemQuantity.value)
db.collection('OrderDatabase').doc(orderID).collection('Basket').doc('testing').set({
ItemName:basketItemName.value,
ItemPrice:basketItemPrice.value,
ItemQuantity:basketItemQuantity.value,
ItemDiscount:basketItemDiscount.value,
ItemSubtotal:basketItemSubtotal.value ,
})
console.log(subtotalArray)
})
console.log(basket)
for(let i = 0; i < subtotalArray.length; i++){
sum += parseFloat(subtotalArray[i]);
}/////////////block ends here
}else if(deliveryMethodInput === 'Ship'){
db.collection('OrderDatabase').doc(orderID).set({
ShippingAddress:shippingAddress,
PickupLocation:"",
BusinessName:businessName,
CustomerType:customerType,
BillingAddress:billingAddress,
CustomerPhoneNumber:customerPhoneNum,
DeliveryMethod:deliveryMethod,
ShipOrPickDate:shipOrPickDate,
PaymentMethod:paymentMethod,
Notes:notes,
OrderDate:orderDate,
OrderStatus:orderStatus,
OrderID:orderID,
salesRepID:salesRepID,
salesRepName:salesRepName,
})
db.collection('CustomerDatabase').get().then((snapshot) => {
snapshot.forEach((doc) => {
if(businessNameValue === doc.data().BusinessName){
let customerID = doc.data().CustomerID;
db.collection('OrderDatabase').doc(orderID).update({
CustomerID:customerID,
})
}
})
})
}
})
})

How to use setUserPointer/getUserPointer from Ammo.js

I want to print names of colliding objects. I made a very simple example.
I created an object to keep a user data:
const userData = { name: name };
I keep this object in a body using setUserPointer:
body.setUserPointer(userData);
I try to get this names using getUserPointer and print them. But I get "undefined" instead of names:
function detectCollison(): void
{
const dispatcher = physicsWorld.getDispatcher();
const numManifolds = dispatcher.getNumManifolds();
for (let i = 0; i < numManifolds; i++)
{
const contactManifold = dispatcher.getManifoldByIndexInternal(i);
const body0 = contactManifold.getBody0();
const body1 = contactManifold.getBody1();
const p0 = body0.getUserPointer();
const p1 = body1.getUserPointer();
console.log("first object: " + p0.name);
console.log("second object: " + p1.name);
}
}
Edited
This is pure TypeScript version. I tried to keep names as a body property but it does not work too. It prints "undefined" instead of names:
(this.body as any).name = name;
physicsWorld.addRigidBody(this.body);
function detectCollison(): void
{
const dispatcher = physicsWorld.getDispatcher();
const numManifolds = dispatcher.getNumManifolds();
for (let i = 0; i < numManifolds; i++)
{
const contactManifold = dispatcher.getManifoldByIndexInternal(i);
const body0 = contactManifold.getBody0();
const body1 = contactManifold.getBody1();
console.log("first object: " + (body0 as any).name);
console.log("second object: " + (body1 as any).name);
}
}
Solution:
const userData = { name: name };
(this.body as any).userData = userData;
function detectCollison(): void
{
const dispatcher = physicsWorld.getDispatcher();
const numManifolds = dispatcher.getNumManifolds();
for (let i = 0; i < numManifolds; i++)
{
const contactManifold = dispatcher.getManifoldByIndexInternal(i);
const body0 = contactManifold.getBody0();
const body1 = contactManifold.getBody1();
const rb0 = (Ammo as any).castObject( contactManifold.getBody0(), Ammo.btRigidBody );
const rb1 = (Ammo as any).castObject( contactManifold.getBody1(), Ammo.btRigidBody );
console.log("first object:", rb0.userData);
console.log("second object:", rb1.userData);
}
}

Having problem in doing operations on values after asynchronous calls

Here i'm calculation two values color and number after calculation i'm updating the values but this is not working
gameSchema.methods.computeBets = async function(){
const game = this;
const greenMultiplier = 2;
const voiletMultiplier = 4.5;
const redMultiplier = 2;
try {
const { gameType } = game;
let model = Schema;
gameType === 'Fast Parity' ? model = FastParity : model = SlowParity;
const gameDetails = await model.findOne({ gameId: game._id });
const { allPlayerBettedBetId } = gameDetails;
let color = {};
let number = {};
await Promise.all(allPlayerBettedBetId.map(async(bet) => {
const betdetails = await UserBet.findById(bet._id);
const { colorBettedOn, numberBettedOn,amountBetted,betType} = betdetails;
// console.log(colorBettedOn, numberBettedOn, amountBetted);
if(betType==='color')
color[colorBettedOn] = color[colorBettedOn] ? color[colorBettedOn] + amountBetted : amountBetted;
if(betType==='number')
number[numberBettedOn] = number[numberBettedOn] ? number[numberBettedOn] + amountBetted : amountBetted;
}));
console.log(color, number);
color.forEach(item => {
if (item.green)
item.green *= greenMultiplier;
if (item.red)
item.red *= redMultiplier;
if (item.voilet)
item.voilet *= voiletMultiplier;
});
let colorCombination = {
"green": color.green,
"green/voilet": color.green+(color.voilet/2),
"red/voilet": color.red+(color.voilet/2),
"red": color.red
};
number.forEach(item => {
item.value *= 2;
})
console.log(number,colorCombination)
return { number, colorCombination };
after await Promise.all console.log(number,color) is working but when i'm updating the values they are not working.I'm not good at async function as i don't have much exprience in that.what mistake i'm doing in the forEach functions

How to get variable in set method

I have an issue with getting a variable in a setter method when I create a class.
In the picture above you can see my method "set quest" returns this (num 1) instead of this.questId (num 2) . How can I get this.questId in "set" and what I am doing wrong? Thank you in advance.
class TestItem {
constructor(testItem) {
this.quest = testItem.quest;
this.answList = testItem.answList;
this.questId = testItem.id;
}
set quest(value) {
console.log(this , this.questId);
let questItem = document.createElement('div');
questItem.classList.add('questItem');
questItem.textContent = `${this.questId}. ${value}`;
this._quest = questItem;
}
set answList(value) {
this._answList = value.map((item, i) => {
let answItem = document.createElement('span');
answItem.classList.add('answItem');
answItem.setAttribute('data-value', item.val);
answItem.textContent = item.answ;
return answItem;
});
}
getQuestBlock() {
let questBlock = document.createElement('div');
questBlock.classList.add(`quest${this.questId}`);
questBlock.append(this._quest);
this._answList.forEach(item => questBlock.append(item));
console.log(questBlock);
return questBlock;
}
}
function createTest(testData) {
let testContainer = document.querySelector('#testContainer');
testData.forEach((item, i) => {
let testItem = new TestItem(item);
let questBlock = testItem.getQuestBlock();
testContainer.append(questBlock);
});
}
document.addEventListener("DOMContentLoaded", createTest.bind(this ,testData));

Why is my function not returning the desired value, however, console.log() does the job?

I know this question might be a little basic but I think I am lacking some important fundamental concept. I am coding in node.js, and I have a function getPostInfo(). In the end, I have a return statement that returns the object that I created. However, when I run it on PowerShell I get no output. Furthermore, when I console.log(object) I get the required answer.
If someone knows what I might be doing wrong, let me know.
P.S. - The major chunks of code in the middle can be skipped as they are just to get information of a webpage
const cheerio = require('cheerio');
const axios = require('axios');
let object = {};
const getPostInfo = async () => {
const {data} = await axios.get('https://www.imdb.com/search/title/?groups=top_1000&ref_=adv_prv');
// console.log(data)
const $ = cheerio.load(data);
const titles = [];
const date = [];
const runtime = [];
const rating = [];
const metascore = [];
const votes = [];
const grossEarning = [];
$('h3 a').each((i, el) => {
titles[i] = $(el).text().trim();
})
$('h3 .lister-item-year').each((i, el) => {
date[i] = $(el).text();
})
$('.runtime').each((i, el) => {
runtime[i] = $(el).text().trim();
});
$('.ratings-imdb-rating').each((i, el) => {
rating[i] = $(el).text().trim();
})
$('.ratings-bar').each((i, el) => {
if ($(el).find('.ratings-metascore .favorable').length > 0) {
metascore[i] = $(el).find('.ratings-metascore .favorable').text().trim();
}
if ($(el).find('.ratings-metascore .mixed').length > 0) {
metascore[i] = $(el).find('.ratings-metascore .mixed').text().trim();
}
})
const nv = [];
$('.sort-num_votes-visible').each((i, el) => {
if($(el).find('span')){
// text-muted has text 'votes:', however we need the number of votes which is in next() span tag
nv[i] = $(el).find('.text-muted').next().text();
votes[i] = nv[i].split('$')[0];
grossEarning[i] = '$' + nv[i].split('$')[1];
}
})
for (let i = 0; i < 50; i++) {
object[i] = {
title: titles[i],
date: date[i],
runtime: runtime[i],
rating: rating[i],
metascore: metascore[i],
votes: votes[i],
grossEarning: grossEarning[i]
};
}
// This does not work but console.log(object) gives me a list of objects
return object
// console.log(object);
}
getPostInfo()

Categories

Resources