Show error alert if value is outside range on button press - javascript

I have a 'calculate' button that takes the quantity entered and multiplies it by the value of an item. JS is below:
function calculate() {
var totalPrice=0;
var price = document.getElementById("itemprice").innerHTML;
var quantity = document.getElementById("quantity").value;
totalPrice=price * quantity;
document.getElementById("totalamount").innerHTML="$" + totalPrice;
//document.write(price * quantity)
}
The above works perfectly for the calculate button. I'm looking to add to this
What I want to also achieve is adding an alert pop up should the "totalprice" result equals zero, a negative number, or NaN (if someone inputs a letter into the quantity box).
So adding to the above something like this:
if ("totalPrice" < 1, NaN)
alert (Please Enter valid quantity)
But I just don't seem to be able to make it work.

totalPrice is variable, if you put it in quotes its a string
if you need 2 conditions in if use || an or operator in your case. Also read: javascript multiple OR conditions in IF statement
Read here how to check for NaN
totalPrice = "not a number"
if (isNaN(totalPrice) || totalPrice < 1) {
alert("Please Enter valid quantity")
}
So you should use:
function calculate() {
var totalPrice = 0;
var price = document.getElementById("itemprice").innerHTML;
var quantity = document.getElementById("quantity").value;
totalPrice = price * quantity;
if (isNaN(totalPrice) || totalPrice < 1) {
alert("Please Enter valid quantity")
} else {
document.getElementById("totalamount").innerHTML = "$" + totalPrice;
}
}

Related

Why does my JavaScript function work but displays "undefined" right after?

Let me preface this by saying I'm a beginner in the world of programming so please excuse my ignorance.
I wrote a simple script for calculating discounts that work, however it displays "undefined" after I execute the code.
let price = prompt("What is the total cost? ");
function total() {
if (price > 250) {
var result = price * discount;
var cost = price - result;
console.log("your total cost will be " + cost);
} else {
console.log("your total cost will be " + price)
}
}
discount = 0.15
console.log(total());
However, when I switch the console.log statements to return statements the undefined message goes away.
let price = prompt("What is the total cost? ");
function total() {
if (price > 250) {
var result = price * discount;
var cost = price - result;
return ("your total cost will be " + cost);
} else {
return ("your total cost will be " + price)
}
}
discount = 0.15
console.log(total());
Why is this? It's confusing me and I don't understand why I'm getting the undefined message.
On the two lines marked "1" you are outputting strings to the console.
In the line marked "2" you are outputting the results of the function total() to the console. But, in your code there is no "result" because you didn't return a value. (Therefore, the value of total() was undefined).
However, when you replaced the lines marked "1" with return(..) in your second code, the total function returned a value (the string). So when you tried to console.log the value of the total() function, it worked.
To look at it another way... if you had a function like this:
function example(){
let value1 = 5+5;
let value2 = 1+1;
}
What would be the value of example()? Nothing -- or undefined. Because how would the function know if you wanted value1, value2 or some combination of the two?
You use the "return" statement to let the function know what is the final value.
function example(){
let value1 = 5+5;
let value2 = 1+1;
return value1*value2;
}
Now the function returns the value (in this case 20).

Can't quite get two variables to add and subtract properly. (Javascript)

Currently I'm trying to use prompts to assign an integer to variables, and then add/subtract based on if the input is a negative or positive value, currently it will add, but it won't subtract.
var creditLimit = parseInt(prompt("What is your credit limit?"))
var initialBalance = parseInt(prompt("What is your current balance?"))
var balanceChange = parseInt(prompt("Please enter a charge or a credit amount"))
var newBalance
if (balanceChange > 0) {
newBalance = initialBalance + balanceChange;
} else if (balanceChange < 0) {
newBalance = initialBalance - balanceChange;
} else {
alert("Please enter a valid integer")
}
I know the alert could probably be something better, but right now I'm just breaking down a credit balance calculator and got held up at this spot.
else if (balanceChange < 0) {
newBalance = initialBalance - balanceChange;
}
The balanceChange < 0 i.e it will be a negative value, so initialBalance - (- balanceChange) = initialBalance + balanceChange
that causing the problem here.
Ah, I just figured it out, I suppose I was trying to use a double negative operation by subtracting a negative input!

How do you write a program in javascript that asks the user to enter a list of numbers, and then find the average of the numbers

I can't get this program to output the average of the entered prompted numbers by a user. How else should i code it? Any help will be appreciated.
var gpas = [];
var gp;
var total = 0;
let count = 0;
var max = 0;
var min = 0;
var out = "";
while (i != "XXX") {
var i = prompt("Enter a gpa or XXX to Stop");
if (i != "XXX") {
gpas.push(i);
}
}
for (var i = 0; i < gpas.length; i++) {
out += gpas[i];
out += "<br/>";
}
count++;
total += gpas[i];
var avg = total / count;
out += avg;
document.getElementById('output').innerHTML += out + "<br/>";
the output is showing "NaN" instead of a valid number.
You can only use a variable that holds the sum of the numbers entered and then just divide it by the total numbers entered.
First approach infinite loop :
The first approach acts as the one you're using. Basically, we'll ask for a new number as long as we don't get the string "XXX".
/**
* #const output the span where to print the average.
**/
const output = document.getElementById('output');
/**
* #var avg stores the sum of the entered numbers.
* #var i keeps track of the number of numbers entered.
**/
let sum = 0,
i = 0;
/** basically while true increment i **/
while (1 && ++i) {
/** ask for a number or "XXX" to exit **/
const n = prompt(`Enter a number or enter "XXX" to exit :`, 0);
/** if "XXX" is entered break the loop (the only way to break that infinite loop) **/
if(n == 'XXX') break;
/** if something else than "XXX" is entered try to cast it to a float **/
sum += parseFloat(n);
}
/** print the average **/
output.textContent = (sum / (i - 1)).toFixed(2); /** why dividing by "i - 1" and not only "i" is because "i" is incremented even when we enter "XXX" **/
<div>average: <span id="output"></span></div>
This approach is not user friendly (the loop can't be exited unless "XXX" is typed) and may consume a lot of resources.
Second approach fixed number of numbers :
This approach asks the user to enter how many number he want to type then we ask him to type as many numbers as the one he typed earlier.
const output = document.getElementById('output');
/**
* #var n the number of numbers the user is going to type.
* #var sum the sum of these numbers.
* #var i a counter used to exit the loop when we reach "n" nummbers typed.
**/
let n = prompt('How many element do you want to enter ?', 2),
sum = 0,
i = 0;
/** while i + 1 < n and no need to manually break the loop **/
while (i++ < n) sum += parseFloat(prompt(`Enter a number (${i} remaining) :`, 0));
output.textContent = (sum / n).toFixed(2); /** now we know how many numbers entered from the beging thanks to the variable "n" **/
<div>average: <span id="output"></span></div>
parseFloat used to parse the numbers (in fact they're strings) entered by the user to floats.
toFixed is used to have only two decimal numbers when calculating the average.
while (i != "XXX") {
var i = prompt("Enter a gpa or XXX to Stop");
if (i != "XXX") {
gpas.push(parseInt(i)); // we need string to number with `parseInt`
}
}
Thanks everyone that contributed. By applying some of the suggestions given, I was able to make it work. I also noticed that the code below does the work too:
var gpas = [];
var gp;
var out = "";
while (i != "XXX")
{
var i = prompt("Enter a gpa or XXX to Stop");
if(i != "XXX"){
gpas.push(parseInt(i));
}
}
let sum = gpas.reduce((a, b) => {
return a + b;
});
sum;
var avg = (sum/gpas.length);
document.getElementById('output').innerHTML += "average =" + avg + "<br/>";
</script>````

Divide input fields with JavaScript

I have 3 input fields:
<input type="text" id ="v0" onkeyup="calculate()"><br>
<input type="text" id ="v1" onkeyup="calculate()"><br>
<input type="text" id="result" onkeyup="calculate()" readonly><br>
What I am trying to do is to count number from 1st input divided by number from 2nd input and displaying it in 3rd input.
function calculate(){
var result = document.getElementById('result');
var el, i = 0, total = 0;
while(el = document.getElementById('v'+(i++)) ) {
el.value = el.value.replace(/\\D/,"");
total = total + Number(el.value);
}
result.value = total;
if(document.getElementById('v0').value =="" && document.getElementById('v1').value ==""){
result.value ="";
}
}
Code is working fine for ADDING this input values, but I need to DIVIDE values from input fields.
I tried to replace "+" with "/" but it breaks the functionality.
You could try a simpler approach like this:
function calculate () {
var input1 = document.querySelector('#v0').value;
var input2 = document.querySelector('#v1').value;
if (input1 && input2) {
document.querySelector('#result').value = (input1 / input2).toFixed(2);
}
}
First of all you have to use "-" for subtraction. But if you want to perform division the problem is that during the first iteration you have total as 0, and it would be:
iteration[1]: 0/anything = 0
iteration[2]: 0/anything = 0
and so on
So you if you want to perform division you need initial value for total, it has to be the 1st input.
Hope that helps.

How do I add inputs together in a do while loop?

hi im very new to javascript and stuck doing my homework. My question is how do I add multiple inputs together in a do while loop? I am supposed to get all the inputs added together then divided by the amount of inputs to get the average. For example if the user were to input 7, 3, 5 and 2 then the answer will be 4.25.This is what I have so far.
var prompt;
var input = prompt("Please enter a number, input a negative number to stop");
var number = input >= 0;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
input = +prompt("Error enter a positive number to start");
}
do {
input = +prompt("Enter another number, a negative to stop");
sum += number;
//inputs added together goes here
} while (input >= 0);
alert(); //inputs added together divided by sum goes here
Hi try this version;
var num = 0, sum = 0, count = 0;
do {
num = parseInt(prompt('Enter Number'));
sum = num >= 0 ? sum+=num : sum;
count = num >= 0 ? count+=1: count; }
while(num >= 0);
console.log(sum + ' count is ' + count);
console.log(sum/count);
Basically I read from prompt, convert the input to integer, I sum the numbers if they are 0 or greater. I add 1 to the count if number is 0 or greater then I divide the sum by the count
Increase the value of sum2 to count the no input. And add a condition that if the user enter a negative value then the total will be divided by the no of inputs.
I have edited your code.
var prompt;
var input = prompt("Please enter a number, input a negative number to stop");
var number;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
input = +prompt("Error enter a positive number to start");
}
do {
input = +prompt("Enter another number, a negative to stop");
number=input;
alert(number);
sum += number;
sum2++;
if(input<0){
sum +=(-number);
alert("average"+(sum/(sum2-1)));
}
//inputs added together goes here
} while (input >= 0);
alert();
Hope it will help.
'use strict';
let input, sum = [];
do {
input = prompt("Enter another number, a negative to stop");
sum.push(input);
} while (input >= 0);
alert(sum.filter((a, b) => {return a + b}) / sum.length);

Categories