This question already has answers here:
How to perform an integer division, and separately get the remainder, in JavaScript?
(18 answers)
Closed 6 months ago.
I want the program to increase the number of notes when the user enters a number higher than 5 if the user enters 12 then its should say that you have 2 notes. I would also my to know if my code could be made more readable and more efficient
const box = document.getElementById('box');
const store = document.getElementById('store');
function notesChecker() {
let num = parseInt(box.value);
if (num / 5 == 0) {
store.textContent = 'You go this number of notes ' + num;
} else {
store.textContent = 'You dont have enough money for notes';
}
}
body {
text-align: center;
}
<h1>Number of notes</h1>
<p>Enter a number and it will tell you the number of notes you will get in £5 notes.</p>
<input id="box" type="number">
<button onclick="notesChecker()">Submit</button>
<div id="store"></div>
It looks like you expected the / operator to perform an integer division, but that is not the case. For example 3 / 5 is 0.6, not 0.
Secondly, you don't want to display the input number in the output message, but the number of notes, for which you need to use the integer division by 5.
Finally, if that quotient is 0, then you should display the other message ("you don't have enough..."), so you need to either swap the messages or invert the if condition.
You can use Math.floor to achieve what you want:
const box = document.getElementById('box');
const store = document.getElementById('store');
function notesChecker() {
let num = parseInt(box.value);
let notes = Math.floor(num / 5);
if (notes > 0) {
store.textContent = "You got this number of notes " + notes;
} else {
store.textContent = "You don't have enough money for notes";
}
}
body {
text-align: center;
}
<h1>Number of notes</h1>
<p>Enter a number and it will tell you the number of notes you will get in £5 notes.</p>
<input id="box" type="number">
<button onclick="notesChecker()">Submit</button>
<div id="store"></div>
const box = document.getElementById('box');
const store = document.getElementById('store');
function notesChecker(){
let num = parseInt(box.value);
if(num<5){
store.textContent ='You dont have enough money for notes';
}else{
num=parseInt(num / 5);
store.textContent='You get this number of notes '+ num ;
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
I'm fairly new to JS and I cannot figure out why my innerHTML is not displaying any output to my 4 input text fields. The ID values for all of the text fields match to the document.getElementByID values, but they aren't getting displayed.
document.getElementById('calculate').addEventListener('click', calculateCoins)
function calculateCoins (){
//converts cents value from string to Int
var cent = parseInt(document.getElementById('cents').value, 10);
/*
calculates # of quarters, displays # of quarters,
and calculates the remainder money
*/
let quarterAmount = Math.floor(cent / 25);
document.getElementById('quarters').innerHTML = quarterAmount;
let quarterRemainder = cent % 25;
/*
calculates # of dimes, displays # of dimes,
and calculates the remainder money
*/
let dimeAmount = Math.floor(quarterRemainder / 10);
document.getElementById('dimes').innerHTML = dimeAmount;
let dimeRemainder = quarterRemainder % 10;
/*
calculates # of nickels, displays # of nickels,
and calculates the remainder money
*/
let nickelAmount = Math.floor(dimeRemainder / 5);
document.getElementById('nickels').innerHTML = nickelAmount;
let nickelRemainder = dimeRemainder % 5;
/*
calculates # of pennies and displays # of pennies
*/
let pennyAmount = Math.floor(nickelRemainder / 1);
document.getElementById('pennies').innerHTML = pennyAmount;
console.log(quarterAmount);
console.log(quarterRemainder);
console.log(dimeAmount);
console.log(dimeRemainder);
console.log(nickelAmount);
console.log(nickelRemainder);
console.log(pennyAmount);
}
To update the input field use .value not .innerHTML
document.getElementById('pennies').value = pennyAmount;
For forms, you need to use the value property instead of the innerHTML property. This is because innerHTML changes the inside code of the tags, while value changes the value attribute of the input.
An example of this is below.
document.querySelector("#text").value = "I'm text!";
<input type="text" name="text" id="text" placeholder="Enter any text here..." />
Also, the value property can also be read to see the current text inputted by the user.
Extra: I also just noticed the below line from your code.
let pennyAmount = Math.floor(nickelRemainder / 1);
This code is actually not nessecary, as division by one is basically just the same number, and flooring it will not change the result.
This may be one possible solution to achieve the desired objective:
This uses document.getElementById(k).value = <<calculated value>>; rather than innerHTML.
Code Snippet
const coins = Object.fromEntries('quarters:25, dimes:10, nickels:5, pennies:1'
.split(',')
.map(ob => ob.split(':'))
.map(([k, v]) => ([k.trim(), {divisor: v, val: 0}])));
const getQR = (num, divisor) => ([
Math.floor(num / divisor), num % divisor
]);
const calculateCoins = () => {
const userInput = +document.getElementById('cents').value.toString();
coins.quarters.val = userInput;
Object.entries(coins).
forEach(([k, {divisor, val}], idx, selfArr) => {
const [d, r] = getQR(val, divisor);
document.getElementById(k).value = d;
if (idx + 1 < selfArr.length) selfArr[idx+1][1].val = r;
});
};
document.getElementById('calculate').addEventListener('click', calculateCoins)
.outer { display: flex; flex-direction: column }
input { width: fit-content; margin: 25px 5px 5px; border: 2px solid black; }
button { width: fit-content; margin: 10px; }
<div class="outer">
<input id="cents">Enter num of cents</input>
<input id="quarters" >Num of quarters</input>
<input id="dimes" >Num of dimes</input>
<input id="nickels" >Num of nickels</input>
<input id="pennies" >Num of pennies</input>
<button id="calculate">Get coins</button>
</div>
Explanation
This solution uses a coins object generated by using known information
Each coin has multiple attributes
The entries of this object are iterated in order to obtain the HTML element information required to render.
Results of the calculation are stored in val for next iteration.
Take a look at this, it worked for me
// Elements
const calculate = document.getElementById("calculate");
const centsEl = document.getElementById("cents");
const quartersEl = document.getElementById("quarters");
const dimesEl = document.getElementById("dimes");
const nickelsEl = document.getElementById("nickels");
const penniesEl = document.getElementById("pennies");
calculate.addEventListener("click", calculateCoins);
function calculateCoins() {
const cents = Number(centsEl.value);
// Quarters calc
let quarterAmount = Math.floor(cents / 25);
quartersEl.innerHTML = quarterAmount;
let quarterRemainder = cents % 25;
// Dimes calc
let dimeAmount = Math.floor(quarterRemainder / 10);
dimesEl.innerHTML = dimeAmount;
let dimeRemainder = quarterRemainder % 10;
// Nickels calc
let nickelAmount = Math.floor(dimeRemainder / 5);
nickelsEl.innerHTML = nickelAmount;
let nickelRemainder = dimeRemainder % 5;
// Pennies calc
let pennyAmount = Math.floor(nickelRemainder / 1);
penniesEl.innerHTML = pennyAmount;
}
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<input type="text" id="cents" />
<button id="calculate">Calculate</button>
<h5>Quarters</h5>
<div id="quarters"></div>
<h5>Dimes</h5>
<div id="dimes"></div>
<h5>Nickels</h5>
<div id="nickels"></div>
<h5>Pennies</h5>
<div id="pennies"></div>
</div>
<script src="src/index.js"></script>
</body>
</html>
How can I make a function to find average from a number insert from prompt? Instead of an array of data.
It is different form all the tutorial on the site because the tutorial and solution here are having a set of data already but instead this question above wants us to calculate the sum of the input number form the prompt.
for example:
const size = parseInt(prompt("insert number")) + 1;
if(size > 0){
const arr = [...Array(size).keys()];
const sum = arr.reduce(function(a, b) { return a + b; }, 0);
alert(sum / size );
}
This question already has answers here:
How to save prompt input into array
(5 answers)
Closed 7 months ago.
I'm busy with a task that requires me to ask the user to keep entering random numbers until the number is "-1". After that I would have to get the average of all the numbers entered excluding the "-1". I've gotten this far with it:
var userNumbers;
while (userNumbers !== "-1") {
userNumbers = prompt("Enter a number");
}
numbersArray = [userNumbers];
console.log(numbersArray);
Try this
// Store all numbers
const numbers = [];
let userNumber;
for(;;){
userNumber = prompt("Enter a number");
if(userNumber === '-1') { break; }
numbers.push(userNumber);
}
// Calculate average
let sum = 0;
let avg = 0;
numbers.forEach((value) => sum += value);
avg = sum / numbers.length
Hello there I have been challenged to write a program in JavaScript despite not really knowing much about it that asks the user for a number and then calculates the factorial of that number. I used already asked questions and managed to get the calculation to work but couldn't get the required output. I have to get it in the following output without using any fancy libraries or extra variables/arrays (which I can't think of how to do) :
(assuming user input is 5):
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
Here is the code I've got so far:
//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number)) {
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0) {
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}
I know there are many similar questions to this as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but don't know where to begin implementing that and I'm only allowed to use that solution.
Unfortunately this is part of a larger program in the challenge and I can only use the following variables:
Number (variable initialised as 0 to hold user input)
Factorial (variable initialised to 1 to hold value of calculated factorial)
Count (variable to hold number of times loop is executed for performing factorial calculation)
Probably you just need to build a string in that loop (on top of calculating the actual value):
let input=parseInt(prompt("Number?"));
let output="";
let result=1;
for(let i=input;i>1;i--){
result*=i;
output+=i+"*";
}
console.log(input+"! is "+output+"1="+result);
The "no-array clause" in your task presumably means that you are not supposed to build an array and use join() on it, like
let arr=[1,2,3,4,5];
console.log(arr.join("*"));
I have updated your code mainly here, Also make sure you are using the same variable num in your code and not number:
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//prompts the user for a positive number
var num = parseInt(prompt("Please enter a positive number"));
console.log(num);
//checks the number to see if it is a string
if (isNaN(num))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (num < 0)
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The " + num + "! is " + factorials.join('*') + " is " + result + ".");
}
This question already has answers here:
Price Calculator based on Quantity [closed]
(4 answers)
Closed 8 years ago.
I am trying to create a simple script to add to a html website.
I need it to calculate the price based on the quantity the user inputs.
For example, a value of 1-1000 will be multiplied by 1.50 and displayed, 1001-5000 multiplied by 1.20 and displayed, 5001-10000 multiplied by 1 and displayed and any number above that would display an error message like "Must be below 10000".
The result is to display in a text field so the user can click submit.
I've been trying to do this in js with no success. If this can be done in any other language please let me know. I'm still learning.
function calc(val) {
if (val < 1 || val > 10000) {
alert("Value must be a positive number under 10,000")
return 0;
}
if (val < 1001) return val*1.5;
if (val < 5001) return val*1.2;
return val;
}
This can be done trough almost every language available for web. Calculating is the most easy thing. For example, in PHP:
$output = $input - 5; // -5
$output = $input + 5; // +5
$output = $input++; // +1
$output = $input * 5; // x5
Javascript plus example:
var input = 5;
var plus = 6;
var output = input+plus;
Javascript min example:
var input = 5;
var plus = 6;
var output = input-plus;