I have a script like this
let x;
let y;
let z;
let obliczone;
document.getElementById("srednia").onclick = function() {
x = document.getElementById("grade1").value;
y = document.getElementById("grade2").value;
z = document.getElementById("grade3").value;
x = Number(x);
y = Number(y);
z = Number(z);
obliczone = Number(obliczone);
obliczone = (x + y + z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="main.css">
<title>Document</title>
</head>
<body>
<label>Ocena 1</label> <input type="text" id="grade1"><br>
<label>Ocena 2</label> <input type="text" id="grade2"><br>
<label>Ocena 3</label> <input type="text" id="grade3"><br>
<label>Oblicz: </label> <button id="srednia">Średnia</button>
<p id="wynik"></p>
<script src="index.js"></script>
</body>
</html>
and if user type in a number with "+" like 2+ I want i to give me 2.5 value and if the input is higher than 6 to break the function. It meant to calculate arithmetic mean of 3 digits and as I wrote earlier it should change ex. 1+ to 1.5
By default when the JavaScript interpreter tries to cast the string to a number and this string contains a symbol it results in a NaN (Not a Number). You can do what you want by replacing the '+' symbol with '.5'.
The new code:
let x;
let y;
let z;
let obliczone;
document.getElementById("srednia").onclick = function () {
x = document.getElementById("grade1").value;
y = document.getElementById("grade2").value;
z = document.getElementById("grade3").value;
const doesXEndsWithPlus = x.endsWith('+')
const doesYEndsWithPlus = y.endsWith('+')
const doesZEndsWithPlus = z.endsWith('+')
if (doesXEndsWithPlus) x = x.replace('+', '.5')
if (doesYEndsWithPlus) y = y.replace('+', '.5')
if (doesZEndsWithPlus) z = z.replace('+', '.5')
x = Number(x);
y = Number(y);
z = Number(z);
obliczone = Number(obliczone);
obliczone = (x + y + z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
This is one way you can do it however if you end up putting more than 3 inputs it can start getting repetitive.
document.getElementById("srednia").onclick = function(){
let obliczone;
let x = document.getElementById("grade1").value;
let y = document.getElementById("grade2").value;
let z = document.getElementById("grade3").value;
if (x.includes('+')) {
x = parseFloat(x.split("+")[0] + ".5")
}
if (y.includes('+')) {
y = parseFloat(y.split("+")[0] + ".5")
}
if (z.includes('+')) {
z = parseFloat(z.split("+")[0] + ".5")
}
obliczone = (x+y+z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
One solution to make it cleaner and more dynamic is to create a helper function formatNumInput(input):
function formatNumInput(input) {
let newNum;
if (input.includes('+')) {
newNum = parseFloat(input.split("+")[0] + ".5")
} else {
newNum = parseFloat(input)
}
return newNum
}
document.getElementById("srednia").onclick = function(){
let obliczone;
let x = document.getElementById("grade1").value;
let y = document.getElementById("grade2").value;
let z = document.getElementById("grade3").value;
x = formatNumInput(x)
y = formatNumInput(y)
z = formatNumInput(z)
obliczone = (x+y+z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
I would like to propose you something a little bit different that could to inspired you and where are not you are not limited only to 3 values of ratings:
//here I define some globals variables
let evaluation = document.getElementById('eval');
let evaluations = [];
let showEval = document.getElementById("evaluation");
let addEval = document.getElementById("addEval");
let average = 0
function showEvals (){
for (let i = 0; i < evaluations.length; i++) {
showEval.innerHTML += `<span>${evaluations[i]}</span>, `
};
};// this is a function to show ratings
function countAverage () {
let sum = 0
for (let i = 0; i < evaluations.length; i++) {
const rating = parseFloat(evaluations[i],10)//here I convert a string go float (Numners() create variable type object not type number
sum += rating
average = (sum/evaluations.length).toFixed(2)// I limited my float to 2 digits
};
document.getElementById("result").innerHTML = "Twoja średnia to " + average
} // this function counts and shows average
addEval.onclick = function(){
evaluations.push(evaluation.value)
showEval.innerHTML = [];
showEvals();
countAverage();
};// here new rangs is pushed to the array of evaluations and it calls ather functions
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<body>
<label for="eval">Dodaj ocene:</label>
<select name="evals" id="eval">
<option value="1">1</option>
<option value="1.5">1+</option>
<option value="2">2</option>
<option value="2.5">2+</option>
<option value="3">3</option>
<option value="3.5">3+</option>
<option value="4">4</option>
<option value="4.5">4+</option>
<option value="5">5</option>
<option value="5.5">5+</option>
<option value="6">6</option>
</select>
</select>
<button id="addEval">Dodaj ocene</button>
<h2>Twoje oceny to:</h2>
<div id="evaluation"></div>
<p id="result"></p>
</body>
</html>
Related
Guys I wanna make an app which can count people, I have it according to the course but I'd like to add the total at the end not the previous entries.
enter image description here
let saveEl = document.getElementById("save-el")
let countEl = document.getElementById("count-el")
let count = 0
function counter() {
count += 1
countEl.textContent = count
}
function save() {
//let countStr = count + "-" caso eu não queira que volte do zero
let countStr = count + " - "
saveEl.textContent += countStr
countEl.textContent = 0
count = 0
}
console.log(count)
Instructions were not clear but I guess you want to "sum up the counts" instead of displaying them separately.
Here's a codepen achieving that, hopefully that works for you ;)
let saveEl = document.getElementById("save-el")
let countEl = document.getElementById("count-el")
let count = 0
function counter() {
count += 1
countEl.textContent = count
}
function save() {
let prevCount = saveEl.textContent ? parseInt(saveEl.textContent) : 0
saveEl.textContent = count + prevCount
countEl.textContent = 0
count = 0
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Counter</title>
</head>
<body>
<h1>Members :</h1>
<button onClick=counter()>counter</button>
<button onClick=save()>save</button>
<p id="count-el"></p>
<hr/>
<p id="save-el"></p>
</body>
</html>
Im trying shuffle the words on mouseover, but to shuffle a new word the previous word have be finished shuffling. This is because otherwise i will get an event.target.innerHTML of a word made up of random letters, if i mouseover the word while the alogorithm is shuffling.
How can i get over this problem, and shuffle any word on mouseover unless that specific word is allready shuffling?
var interv = 'undefined'
var canChange = false
var globalCount = 0
var count = 0
var isGoing = false
document.querySelectorAll("span").forEach((button) => button.addEventListener("mouseover", shuffleWord));
let texxt = document.querySelector('p');
console.log(texxt);
function shuffleWord(event){
let INITIAL_WORD = event.target.innerHTML;
if(isGoing) return;
var randomWord = getRandomWord(INITIAL_WORD);
event.target.innerHTML = randomWord;
isGoing = true;
interv = setInterval(function() {
var finalWord = ''
for(var x=0;x<INITIAL_WORD.length;x++) {
if(x <= count && canChange) {
finalWord += INITIAL_WORD[x]
} else {
finalWord += getRandomLetter()
}
}
event.target.innerHTML = finalWord
if(canChange) {
count++
}
if(globalCount >= 20) {
canChange = true
}
if(count>=INITIAL_WORD.length) {
clearInterval(interv)
count = 0
canChange = false
globalCount = 0
isGoing = false
}
globalCount++
},40)
function getRandomLetter() {
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
return alphabet[rand(0,alphabet.length - 1)]
}
function getRandomWord(word) {
var text = word;
console.log(text);
INITIAL_WORD = event.target.innerText;
var finalWord = ''
for(var i=0;i<text.length;i++) {
finalWord += text[i] == ' ' ? ' ' : getRandomLetter()
}
return finalWord
}
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<span>SOME RANDOM TEXT</span>
<br>
<br>
<span>MORE TEXT</span>
<br>
<br>
<span>EVEN MORE TEXT</span>
<script src="script.js"></script>
</body>
</html>
Below is the function for insertion sort. I want that user should give the input from html form as an array elements instead of hard coding the elements of array. I have tried several techniques but in vain.
function insertionSort (inputArr) {
let length = inputArr.length;
for (let i = 1; i < length; i++) {
let key = inputArr[i];
let j = i - 1;
while (j >= 0 && inputArr[j] > key) {
inputArr[j + 1] = inputArr[j];
j = j - 1;
}
inputArr[j + 1] = key;
}
return inputArr;
};
let inputArr = [2,4,5,36,2,6,26,8,3,7]; // I want here user input which comes from html form instead of hard-coding elements of array like this
insertionSort(inputArr);
console.log(inputArr);
// Event listner
function getData() {
let userData = document.getElementById('data').value;
return userData;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Insertion Sort In JavaScript</title>
</head>
<body>
<h1>Insertion Sort in JavaScript</h1>
<form action="#">
<label for="data">Write Random Numbers</label>
<input type="text" name="data" id="data">
<button onclick="getData()">Submit</button>
</form>
<div id="printData"></div>
<script src="insertionsort.js"></script>
I tried changing the value into an integer with parseInt it still didn't work and whenever I run it it always just says NaN.
I tried changing the variables a1, b1 and c1 to number directly by (writing a1 = 3 for example) and it worked fine then. I'm still a novice and I don't know what to do.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<link rel="stylesheet" href="style1.css">
</head>
<body>
<h1> Find c or know if it's a right-angle triangle?</h1>
<div id="isIt">
<h5>Please enter the lengths of each side.</h5>
//input area where you enter the sides of the triangle
<input id="a" type="number" min="0.1" placeholder="a">
<input id="b" type="number" min="0.1" placeholder="b">
<input id="c" type="number" min="0.1" placeholder="c">
<br>
<button onclick="isIt()">is it a Triangle?</button>
<button onclick="findc()">What is c?</button>
</div>
<p id="answer"></p>
<script>
//where my problem is
var a1 = (document.getElementById('a').value;
var b1 = document.getElementById('b').value;
var c1 = document.getElementById('c').value;
var m = Math.sqrt( a1*a1 + b1*b1);
//function to know if its a triangle
function isIt() {
if (c1 === m) {
document.getElementById('answer').innerHTML = 'YES!';
}else{
var trueC0 = Math.sqrt((a*a) + (b*b));
var trueC2 = trueC0.toString();
document.getElementById('answer').innerHTML = "NO! c needs to be " + trueC2 + " too be a
right-angle triangle";
}
}
//function to calculate c
function findc() {
var c = Math.sqrt( a*a + b*b);
document.getElementById('answer').innerHTML = c.toString() ;
}
</script>
</body>
</html>
There are some issues with this code. First is that you're declaring var a1 b1 c1 and m outside your isIt function. So those variables are created and initialized only when your code loads and not in every call to isIt. That means that when you call isIt those variables aren't updated with the new values on the inputs and the calculations are made with whatever value they had on page load. Second is that here var trueC0 = Math.sqrt((a*a) + (b*b)) and here var c = Math.sqrt( a*a + b*b); you're using var a and b which doesn't exist. That's the reason why it returns Nan. I believe they should be a1 and b1. Here is the working code:
<script>
//function to know if its a triangle
function isIt() {
var a1 = document.getElementById('a').value;
var b1 = document.getElementById('b').value;
var c1 = document.getElementById('c').value;
var m = Math.sqrt(a1 * a1 + b1 * b1);
if (c1 === m) {
document.getElementById('answer').innerHTML = 'YES!';
} else {
var trueC0 = Math.sqrt((a1 * a1) + (b1 * b1));
var trueC2 = trueC0.toString();
document.getElementById('answer').innerHTML = "NO! c needs to be " + trueC2 + " too be a right-angle triangle";
}
}
//function to calculate c
function findc() {
var a1 = document.getElementById('a').value;
var b1 = document.getElementById('b').value;
var c1 = document.getElementById('c').value;
var m = Math.sqrt(a1 * a1 + b1 * b1);
var c = Math.sqrt(a1 * a1 + b1 * b1);
document.getElementById('answer').innerHTML = c.toString();
}
</script>
Also note that here if (c1 === m) c1 and m can be floating numbers and Javascript has issues with floating numbers comparison. It is very common that it returns false even when the numbers are equal. There are libraries for doing that.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<link rel="stylesheet" href="style1.css">
</head>
<body>
<h1> Find c or know if it's a right-angle triangle?</h1>
<div id="isIt">
<h5>Please enter the lengths of each side.</h5>
//input area where you enter the sides of the triangle
<input id="a" type="number" min="0.1" placeholder="a">
<input id="b" type="number" min="0.1" placeholder="b">
<input id="c" type="number" min="0.1" placeholder="c">
<br>
<button onclick="isIt()">is it a Triangle?</button>
<button onclick="findc()">What is c?</button>
</div>
<p id="answer"></p>
<script>
//where my problem is
//function to know if its a triangle
function isIt() {
var a1 = document.getElementById('a').value;
var b1 = document.getElementById('b').value;
var c1 = document.getElementById('c').value;
var m = Math.sqrt( a1*a1 + b1*b1);
if (c1 == m) {
document.getElementById('answer').innerHTML = 'YES!';
}else{
document.getElementById('answer').innerHTML = "NO! c needs to be " + m + " too be a right-angle triangle"
}
}
//function to calculate c
function findc() {
var a1 = document.getElementById('a').value;
var b1 = document.getElementById('b').value;
var c = Math.sqrt( a1*a1 + b1*b1);
document.getElementById('answer').innerHTML = c;
}
</script>
</body>
</html>
When the script loads, your a1,b1,c1 and m initialized, but at that time, user haven't entered any value, so all of them are undefined. When function isIt and findC execute, they are using undefined values for calculation. That's why your code doesn't work. Also m is a number, but c1 is string, you will need == to compare them, or you need to cast c1 to number if you want to use === for comparing them.
Hope it helps
This is my JavaScript-Code
it should calculate how much CO2 produces a person per km. it is a school subject an i am just at the beginning so please go easy on me...
also i just registered to stockoverflow
i am also a newbee here...i thank you in advance...
window.onload = function () {
// CO2 Verbrauch = ((fs / ksv) * ta) / am)+(fs*0.14)
var btn = document.getElementById('btn'); // Initiate Calulation
var ta = document.getElementById('treibstoffart') // Selector
var benzin = document.getElementById('benzin'); // Option 1
var diesel = document.getElementById('diesel'); // Option 2
var autogas = document.getElementById('autogas'); // Option 3
var ksv = document.getElementById('Kraftstoffverbrauch'); // Inputfield
var fs = document.getElementById('Fahrtstrecke'); // Inputfield
var am = document.getElementById('Anzahl der Mitfahrer'); // Inputfield
var ausgabe = document.getElementById('ergebnis'); // Result
every option has a fixed number
var tsa = function () { //////// NOT SURE WHAT IS WRONG
if (benzin) {
benzin.value = 2.33;
} else if (diesel) {
diesel.value = 2.64;
} else if (autogas) {
autogas.value = 1.64;
}
}; // End of function (treibstoffart)
btn.onclick = function () {
ausgabe.innerText = (((fs.value * 1 / ksv.value * 1) * tsa) / am.value * 1) + (fs.value * 0.14); //////// TSA is added here
};
} // End of function (window.onload)
This is the HTML Code
i am using Bootstrap as you can see but i think the most problem is the selector i use for the function.
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Übung 1 Rechner</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="uebung_1.css">
<script src="uebung_1.js"></script>
</head>
<body>
<section>
<form class="form-inline">
<select id="treibstoffart" class="form-control">
<option value="" selected>... auswählen ...</option>
<option value="benzin">Benzin</option>
<option value="diesel">Diesel</option>
<option value="autogas">Autogas</option>
<input id="Kraftstoffverbrauch" type="text" placeholder="Kraftstoffverbrauch (Liter/100km)" value=""
class="form-control">
<input id="Fahrtstrecke" type="text" placeholder="Fahrtstrecke (in km)" value="" class="form-control">
<input id="Anzahl der Mitfahrer" type="text" placeholder="Anzahl der Mitfahrer" value=""
class="form-control">
<button type="button" id="btn" class="btn btn-primary" value="">Berechnen</button>
<button type="reset" class="btn btn-danger" value="Reset">Clear</button>
</form>
</section>
<section>
<p>Das Ergebnis wird hier Angezeigt</p>
<p id="ergebnis"></p>
<p>Weitere Ergebnisse für Reisebus, Bahn, Flugzeug</p>
</section>
</body>
</html>
if have found the answer
window.onload = function () {
// CO2 Verbrauch = ((fs / ksv) * ta) / am)+(fs*0.14)
let btn = document.getElementById('btn');
let ausgabe = document.getElementById('ergebnis'); // Result
let ta = document.getElementById('treibstoffart'); // Selector
let ksv = document.getElementById('Kraftstoffverbrauch'); // Inputfield
let fs = document.getElementById('Fahrtstrecke'); // Inputfield
let am = document.getElementById('Anzahl der Mitfahrer'); // Inputfield
btn.onclick = function () { // Initiate Calulation
ausgabe.innerText = (((fs.value * 1 / ksv.value * 1) * ta.value) / am.value * 1) + (fs.value * 0.14);
};
} // End of function (window.onload)