I'm starting to learn javascript, and I'm trying to make a calculator app to solve simple harmonic motion. and made a js code to solve automatically if there are values from the input fields.
similar mechanics on this website when you put values it automatically solves and you can delete the value to solve another one https://www.omnicalculator.com/physics/displacement
const mass_event = document.getElementById("mass");
const k_event = document.getElementById("spring-constant");
const period_event = document.getElementById("period");
mass_event.addEventListener("input", solve);
k_event.addEventListener("input", solve);
period_event.addEventListener("input", solve);
function solve () {
var mass = document.getElementById("mass").value;
var konstant = document.getElementById("spring-constant").value;
var time = document.getElementById("period").value;
m = Number(mass);
k = Number(konstant);
t = Number(time);
if (m && k != 0) {
period = (2 * Math.PI * Math.sqrt((m/k)));
document.getElementById("period").value = (period);
} else if (k && t != 0) {
mass_kg = (Math.pow(t, 2) * k) / (4 * Math.pow(Math.PI, 2));
document.getElementById("mass").value = (mass_kg);
} else if (m && t != 0) {
spring_constant = (4 * Math.pow(Math.PI, 2) * m) / (Math.pow(t, 2));
document.getElementById("spring-constant").value = (spring_constant);
}}
It works but when there are already 2 values you cant delete the input values to solve for another. I'm trying to do this so that i can remove the solve button
Related
I have a random number generator that gives me a value between 1 and 6 (N).
I want to change the image SRC based on what number I get.
for instance, I have 6 images named [image1, image2, image3, image4, image5, image6].
let N = Math.random() * 6;
N = Math.floor(N);
document.querySelector(".img").src = `images/image${N}.png `;
I think the problem is caused by JS parsing images/img${N}.png as a HTML code due to ${N} being JavaScript code and HTML not being able to assign a value to it.
is there another way of writing this without using if / else if for every value of N?
like so =>
let N = Math.random() * 6;
N = Math.floor(N);
if (N === 1) {
document.querySelector(".img1").src = "images/image1.png";
} else if (N === 2) {
document.querySelector(".img1").src = "images/image2.png";
} else if (N === 3) {
document.querySelector(".img1").src = "images/image3.png";
} else if (N === 4) {
document.querySelector(".img1").src = "images/image4.png";
} else if (N === 5) {
document.querySelector(".img1").src = "images/image5.png";
} else {
document.querySelector(".img1").src = "images/image6.png";
}
Your problem is a superfluous space at the end of the template/string
document.querySelector(".img").src = `images/image${N}.png `;
// ^
and missing one for one based counting.
Your actual random values are 0 ... 5, but you need 1 ... 6.
You could take a shorter approach by moving the random/flooring part into the expression.
document.querySelector(".img").src = `images/image${Math.floor(Math.random() * 6) + 1}.png`;
const n = Math.floor(Math.random() * 6) + 1;
console.log(`images/image${n}.png`);
You can use array index like this:
let N = Math.random() * 6;
N = Math.floor(N);
const imgs = [image1, image2, image3, image4, image5, image6]
document.querySelector(".img1").src = imgs[N];
You can use something like this :
let N = 6 // no of images
const imageBase='images/image';// relative or absolute url
document.querySelector(".img").src = `${imageBase}${Math.floor(Math.random() * N)}.png`;
I was trying a very simple thing with javascript, to create a minesweeper grid.
gridsize=9;
//grid initialisation
var grid=Array(gridsize).fill(Array(gridsize).fill(null));
// this comes from <https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range>
function randint(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
nbombs=20;
insertedbombs=0;
while (insertedbombs<nbombs){
rx=randint(0,gridsize-1);
ry=randint(0,gridsize-1);
if (grid[rx][ry] == null){
insertedbombs++;
grid[rx][ry]='b';
}
}
The while loop hangs, both in Chrome and Firefox consoles, all the values of the grid are filled, not just 20, i've no idea why, i guess i have some wrong understanding of javascript language, because the same code in python works.
Working python code:
grid= [[None for i in range(9)]for i in range(9)]
nbombs=20;
insertedbombs=0;
while (insertedbombs< nbombs):
rx=random.randint(0,8)
ry=random.randint(0,8)
if (grid[rx][ry]== None):
grid[rx][ry]='b'
insertedbombs+=1
The issues is that Array#fill doesn't do what you think it does.
In your example you create a SINGLE array Array(gridsize).fill(null) and then you put that array at each index of the outer array. Meaning that your grid actually contains the same array, 9 times over. So when you assign grid[0][0] you actually assign grid[0][0], grid[1][0], grid[2][0], grid[3][0], etc... all at once (ish).
const gridSize = 9;
//grid initialisation
const grid = Array(gridSize).fill(Array(gridSize).fill(null));
console.log(grid[0] === grid[1]);
grid[0][0] = 10;
console.log(grid[0][0], grid[0][0] === grid[1][0]);
What you want to do, is first fill the array with some dummy value, like null. Then map over the array and replace each entry with its own copy of Array(gridsize).fill(null).
const gridSize = 9;
//grid initialisation
const grid = Array(gridSize)
.fill(null)
.map(() => Array(gridSize)
.fill(null)
);
const randInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
const nbombs = 20;
let insertedbombs = 0;
while (insertedbombs < nbombs){
const rx = randInt(0, gridSize - 1);
const ry = randInt(0, gridSize - 1);
if (grid[rx][ry] === null){
insertedbombs += 1;
grid[rx][ry] = 'b';
}
}
console.log(grid);
i am trying to create the driver performance assistant.
when i start up the page it needs to read the variable from the last time and use that to count up.
(i have created a dashboard that reads data through a plugin from a game. i am trying to create the driver performance assistant from DAF (truck brand). the way it should work is when rolling out the vehicle it counts up a variable accordingly to the time it is rolling out (this part i have created and it works) now my problem is. i am also trying to save it in the localstorage so it wont get lost. but the variable is doing weird things when i tries to read the localstorage data.
this code only needs to be in javascript.
// variables for driver score
var startBrake = 0;
var endBrake = 0;
var timeDiffBrake = 0;
var countBrake = localStorage.getItem('brake');
var startRollout = 0;
var endRollout = 0;
var timeDiffRollout = 0;
var countRollout = localStorage.getItem('rollout');
var speed = Math.abs(data.truck.speed > 0 ? Math.floor(data.truck.speed) : Math.round(data.truck.speed));
var throttle = utils.formatFloat(data.truck.gameThrottle, 2);
var serviceBrake = utils.formatFloat(data.truck.userBrake, 2);
var retarder = data.truck.retarderBrake;
var engineBrake = data.truck.motorBrakeOn;
var cruiseControl = data.truck.cruiseControlOn;
var fuelConsumption = data.truck.fuelAverageConsumption * 100;
// ANTICIPATE
// Braking to long
if (speed >= 50) {
if (serviceBrake < 0.1) {
startBrake = new Date();
} else if (serviceBrake > 0.25) {
endBrake = new Date();
timeDiffBrake = (endBrake - startBrake) / 1000;
if (timeDiffBrake > 5) {
countBrake -= 0.01;
// add "te lang remmen" display
}
}
}
localStorage.setItem('brake', countBrake);
// Rolling out
if (speed > 30 && speed < 89) {
if (throttle > 0) {
startRollout = new Date();
} else if (throttle < 0.05 && serviceBrake == 0) {
endRollout = new Date();
timeDiffRollout = (endRollout - startRollout) / 1000;
if (timeDiffRollout > 1) {
countRollout += 0.01;
// maybe add display
}
}
}
localStorage.setItem('rollout', countRollout);
// EFFICIENT BRAKING
var brake = localStorage.getItem('brake');
var rollout = localStorage.getItem('rollout');
var anticipate = brake + rollout;
var efficientBraking = 0; // haven't done this yet
var driverScore = Math.round((efficientBraking + anticipate) / 2);
data.drivingScorePercent = driverScore <= 0 ? 0 : driverScore >= 100 ? 100 : driverScore;
the main problem is this variable
var countRollout = localStorage.getItem('rollout');
it keeps saying my data is NAN (i think undefined)
i changed the lines to what "mister jojo" suggested but somehow i get some wierd data from the localstorage. i assumed that a "var += 0.01" would count 0.01 up but somehow it goes like this "0.010.010.010.010.01" instead of 0.01, 0.02, 0.03.
When you are declaring the countBrake and countRollout variables, the value are undefined because you didn't set the values to localStorage yet. So, you can check whether there is already a value set in localStorage and set default value incase the value isn't set yet:
var countBrake = localStorage.getItem('brake') !== undefined ? localStorage.getItem('brake') : 0;
var countRollout = localStorage.getItem('rollout') !== undefined localStorage.getItem('rollout') : 0;
more simple for Shuvo answer is
with the use of the Nullish coalescing operator (??)
var countBrake = localStorage.getItem('brake') ?? 0
, countRollout = localStorage.getItem('rollout') ?? 0
;
I can't seem to find any solutions.
I want to create a form that collects 4 nicknames after submit a form and then displays them all randomly in html code using javascript
My 4 input values are now in an array.
I have to display them randomly in two different teams.
I'm trying to get a random index, and as long as it's different from the ones already assigned to avoid one person being on both teams.
This code works, but sometimes, one player is assigned to 2 teams. Then, the randomizer doesn't work... Do you have an idea ?
function getRandomNumber(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function getData() {
let joueur1 = document.querySelector("#player1").value;
let joueur2 = document.querySelector("#player2").value;
let joueur3 = document.querySelector("#player3").value;
let joueur4 = document.querySelector("#player4").value;
playerList.push(player1.value);
playerList.push(player2.value);
playerList.push(player3.value);
playerList.push(player4.value);
randomNumber1 = getRandomNumber(playerList.length);
last1 += randomNumber1;
random1.textContent = playerList[randomNumber1];
do {
randomNumber2 = getRandomNumber(playerList.length);
} while (randomNumber2 == last1 && last4 && last3);
last2 += randomNumber2
random2.textContent = playerList[randomNumber2];
do {
randomNumber3 = getRandomNumber(playerList.length);
} while (randomNumber3 == last1 && last2 && last4);
last3 += randomNumber3
random3.textContent = playerList[randomNumber3];
do {
randomNumber4 = getRandomNumber(playerList.length);
}while (randomNumber4 == last1 && last2 && last3)
random4.textContent = playerList[randomNumber4];
last4 += randomNumber4
}
Thanks for your help !
Here is a simple way of getting a random item from your array
Here you add your items into array
let joueur1 = document.querySelector("#player1").value;
let joueur2 = document.querySelector("#player2").value;
let joueur3 = document.querySelector("#player3").value;
let joueur4 = document.querySelector("#player4").value;
let playerList=[];
playerList.push(joueur1);
playerList.push(joueur2);
playerList.push(joueur3);
playerList.push(joueur4);
Then, Here is how you can get randomized content
let randomPlayer = playerList[Math.floor(Math.random() * playerList.length)];
Math.random() will never be 1. The largest index is always one less than the length of the array
I've created a calculator that requires a value in either months or years in order to perform a calculation. The calculator works with one exception: It is required that the two input fields update based on the value of each other. here's an example of the behavior I am attempting to recreate:
https://www.bankrate.com/calculators/mortgages/loan-calculator.aspx
I apologize in advance if the following example reads poorly, but here it goes:
If a user enters 72 'months', the 'years' input will divide months by 12 and display the result. After doing a little tooling around, I found that using [a, b] = [b*12, a/12] gets me halfway there. The problem I'm running into is that once values have been entered, the value of the most recently updated input is updated with the previous value (including the calculation). For example, User enters 60 months > years is populated with the value of 5 > user changes months to a value of 72 > years is populated with a value of 6 > months is automatically populated with a value of 60 (years remains at a value of 6)
Here's the JS:
const loan = () => {
let principal = document.getElementById('principal')
let interestRate = document.getElementById('interestRate')
let terms = document.getElementById('terms')
let termsInYears = document.getElementById('termsInYears')
let payment = document.getElementById('payment')
let total = document.getElementById('total')
let totalInterest = document.getElementById('totalInterest')
let closingCosts = document.getElementById('closingCosts')
let netAfterFees = document.getElementById('netAfterFees')
let totalFeesAndInterest = document.getElementById('totalFeesAndInterest')
let trueCost = document.getElementById('trueCost')
let amount = parseFloat(principal.value)
let interest = parseFloat(interestRate.value) / 100 / 12
let payments = parseFloat(terms.value)
let fees = parseFloat(closingCosts.value)
if(!fees) {
closingCosts.value = 0
}
[terms.value, termsInYears.value] = [termsInYears.value*12, terms.value/12]
let x = Math.pow(1 + interest, payments)
let monthly = (amount * x * interest) / (x-1)
let totalPay = (monthly * payments)
if (isFinite(monthly) && payment) {
payment.innerHTML = monthly.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
netAfterFees.innerHTML = (amount - fees).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
total.innerHTML = (totalPay).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
totalInterest.innerHTML = ((monthly * payments) - amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
totalFeesAndInterest.innerHTML = (totalPay - amount + fees).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
trueCost.innerHTML = (((totalPay - amount + fees) / amount)*100).toFixed(2)
} else {
payment.innerHTML = '0'
netAfterFees.innerHTML = '0'
total.innerHTML = '0'
totalInterest.innerHTML = '0'
totalFeesAndInterest.innerHTML = '0'
trueCost.innerHTML = '0'
}
}
I can't speak on the quality of the working calculator given my experience level. However, it does work. I'm just having one heck of a time getting past this [likely silly] input exchange.
Any help would be greatly appreciated!
I ended up solving this issue using querySelector and then adding an event listener for each input:
document.querySelector('#terms').addEventListener('input', (e) => {
termsInYears.value = e.target.value / 12
})
document.querySelector('#termsInYears').addEventListener('input', (e) => {
terms.value = e.target.value * 12
})