Javascript : multiple remainder pricing table - javascript

I have been given this logic table that I need to use if else statement to get a promotion price based on user input.
How to declare that logic table in javascript? So that I can print out the correct output based on the table.
For example; if user input is 5, so, I need an expected output of (price 3 + price 2).
function checkQuantity() {
let userInput = document.getElementById('quantity').value;
userInput = Number(userInput); //Convert string to number data type
var pizzaPrice = 6.45;
var pizzaPrice2 = 12.00;
var pizzaPrice3 = 14.00;
if (!userInput) {
console.log("Please enter a valid pizza quantity");
} else if (isNaN(userInput)) {
console.log("Error!!");
} else if (userInput < 1) {
console.log("Minimum pizza order is 1.");
} else {
document.getElementById('message').innerHTML = 'Number of pizza : ' + //Price hasn't been declared yet;
}
return false;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ordering form</title>
<script src="linked.js"></script>
</head>
<body>
<h1>PizzasOnly ordering form</h1>
<p>Simply enter the number of pizzas you want into the input below to find out the cost of your order</p>
<form action="#" method="post" id="orderForm" onsubmit="return checkQuantity()">
<p>
<label for="quantity">Enter number of pizzas wanted:</label>
<input name="quantity" id="quantity" value="">
</p>
<p>
<input value="Total cost" type="submit">
</p>
</form>
<div id="message"></div>
</body>
</html>

The formula can be assembled as a one-liner:
~~(i/3)*price + xtra[i%3]
~~ (the repeated application of the "bitwise NOT operator") is a shorthand notation for Math(floor(), % is the modulo operator that will return the remainder of a division, the rest should be clear.
const price=(i,p3=14,xtr=[0,6.45,12])=>~~(i/3)*p3 + xtr[i%3];
[...Array(14)].map((_,i)=>i+1).concat([50,100,1500,1276]).forEach(i=>console.log(i,price(i)) )
In this later version I defined the function price(). It can be called with one argument (i: number of pizzas) as you can see above.
The optional arguments p3 (price for a bundle of 3) and xtr (addon for zero, one or two extra pizzas) can be supplied if you want to use a different pricing structure than the default one, see here:
const price=(i,p3=14,xtr=[0,6.45,12])=>~~(i/3)*p3 + xtr[i%3];
[...Array(14)].map((_,i)=>i+1).concat([50,100,1500,1276]).forEach(i=>console.log(i,price(i,16,[0,6,11])) )

Related

Multiplying in javascript with textbox

I am a beginner javascript programmer. I made a very simple program to multiply 2 numbers with textbox. At first it worked. But then I wrote some logic to avoid some bugs. And some of the logics are not working. could anybody take a look at this code and tell me what's wrong here:
let text1;
let text2;
let ans;
// returning the value inside the texbox.
document.getElementById('mul').onclick=()=>{
text1=document.getElementById('text1').value;
text1 = Number(text1);
text2=document.getElementById('text2').value;
text2 = Number(text2);
// checking if it is a number or not
if(isNaN(text1)||isNaN(text2)){
document.getElementById('P').innerHTML='it should be a number. Not alphabets or symbols';
}
// checking if it is an integer or not.
else if(text1.length>0 && Number.isInteger(text1)==false && text2.length>0 && Number.isInteger(text2)==false){
document.getElementById('P').innerHTML='You cant multiply with decimal points';
}
// checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
else if(text1.length==0||text2.length==0){
document.getElementById('P').innerHTML='you cant do any calculations with blank textbox';
}
// else, if it has no problem just multiply.
else{
let ans=BigInt(text1*text2);
document.getElementById('P').innerHTML=ans;
document.getElementById('zero').innerHTML='&times';
}
}
I am getting the correct output when i enter the integer values in the text box and click submit button. But the problem is both the else if statement is not working. when i give the input as a float value it is not doing anything. It has to display the message , but it is not. same when i dont give any input and click the submit button. It is not displaying the message. Why does this happen. How to solve this?
HTML of this code:
<!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>calculator</title>
<link rel="stylesheet" href="calculator.css">
</head>
<body align="center">
<input type="text" id="text1" placeholder="enter a value">
<p id="zero"></p><input type="text" placeholder="enter a value"id="text2">
<br><br><br><p id="P"></p>
<br><br><br><br><br><button id="mul">Multiply</button>
<br><br><br><br><br><button id="sub">Subtract</button>
<br><br><br><br><br><button id="div">Divide</button>
<br><br><br><br><br><button id="add">Add</button>
<script src="calculator.js"></script>
</body>
</html>
You used double equal signs and not triple. in order to check for strict equality.
now it works:
let text1;
let text2;
let ans;
// returning the value inside the texbox.
document.getElementById('mul').onclick = () => {
text1 = document.getElementById('text1').value;
text1 = Number(text1);
text2 = document.getElementById('text2').value;
text2 = Number(text2);
// checking if it is a number or not
if (isNaN(text1) || isNaN(text2)) {
document.getElementById('P').innerText = 'it should be a number. Not alphabets or symbols';
}
// checking if it is an integer or not.
else if (!(text1.length > 0 && Number.isInteger(text1)) && !(text2.length > 0 && Number.isInteger(text2))) {
document.getElementById('P').innerHTML = 'You cant multiply with decimal points';
}
// checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
else if (text1.length === 0 || text2.length === 0) {
document.getElementById('P').innerHTML = 'you cant do any calculations with blank textbox';
}
// else, if it has no problem just multiply.
else {
let ans = BigInt(text1 * text2);
document.getElementById('P').innerHTML = ans;
document.getElementById('zero').innerHTML = '&times';
}
}
<input type="text" id="text1" placeholder="enter a value">
<p id="zero"></p><input type="text" placeholder="enter a value"id="text2">
<br><br><br><p id="P"></p>
<br><br><br><br><br><button id="mul">Multiply</button>
<br><br><br><br><br><button id="sub">Subtract</button>
<br><br><br><br><br><button id="div">Divide</button>
<br><br><br><br><br><button id="add">Add</button>
<script src="calculator.js"></script>
This should work. There is no length property available in Number. So if you cast your inputs to Number, inputValue.length will no longer work.
let text1;
let text2;
let ans;
// returning the value inside the texbox.
document.getElementById('mul').onclick=()=>{
text1=document.getElementById('text1').value;
text1 = Number(text1);
text2=document.getElementById('text2').value;
text2 = Number(text2);
// checking if it is a number or not
if(isNaN(text1)||isNaN(text2)){
document.getElementById('P').innerHTML='it should be a number. Not alphabets or symbols';
}
// checking if it is an integer or not.
else if(!Number.isInteger(text1) || !Number.isInteger(text2)){
document.getElementById('P').innerHTML='You cant multiply with decimal points';
}
// checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
else if(!text1.length||!text2.length){
document.getElementById('P').innerHTML='you cant do any calculations with blank textbox';
}
// else, if it has no problem just multiply.
else{
let ans=text1*text2;
document.getElementById('P').innerHTML=ans;
document.getElementById('zero').innerHTML='&times';
}
}
<!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>calculator</title>
<link rel="stylesheet" href="calculator.css">
</head>
<body align="center">
<input type="text" id="text1" placeholder="enter a value">
<p id="zero"></p><input type="text" placeholder="enter a value"id="text2">
<br><br><br><p id="P"></p>
<br><br><br><br><br><button id="mul">Multiply</button>
<br><br><br><br><br><button id="sub">Subtract</button>
<br><br><br><br><br><button id="div">Divide</button>
<br><br><br><br><br><button id="add">Add</button>
<script src="calculator.js"></script>
</body>
</html>
let text1, text2;
// returning the value inside the texbox.
document.getElementById('mul').onclick=()=>{
text1=parseInt(document.getElementById('text1').value)
text2=parseInt(document.getElementById('text2').value)
// checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
if(text1.length==0){
document.getElementById('P').innerHTML='you cant do any calculations with blank textbox';
}
// else, if it has no problem just multiply.
else{
document.getElementById('P').innerHTML=text1*text2;
document.getElementById('zero').innerHTML='&times';
}
}
<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>calculator</title>
<link rel="stylesheet" href="calculator.css">
</head>
<body style="text-align: center;">
<input type="number" min="0" id="text1" placeholder="enter a value">
<p id="zero"></p><input type="number" min="0" placeholder="enter a value" id="text2">
<br><br><br><p id="P"></p>
<br><br><br><br><br><button id="mul">Multiply</button>
<br><br><br><br><br><button id="sub">Subtract</button>
<br><br><br><br><br><button id="div">Divide</button>
<br><br><br><br><br><button id="add">Add</button>
<script src="calculator.js"></script>
</html>
Explaining code:
First, I rewrite all input types to number, so now user can't write any symbols except numbers, and I'm removed isNaN check because of reason I said before. Also, I used only text1 and text2 variables and removed ans variable because calculating is doing right before writing calculated number in innerHTML. Plus numbers automatically parsed as integers, so I removed integer check.
Here's your app working 100%.
The reason your code wasn't working because there is no length property on a number type. length is only on arrays and strings.
Some issues with your code:
text1 and text2 shouldn't be let variables at the top of the global scope. They should be pointers to their respective DOM nodes, which .value can be used on at any time.
Instead of using Element.onclick, use Element.addEventListener('click', callback) instead.
Avoid using innerHTML. Is is best practice to use textContent or innerText (textContent is best).
You can set an input element's type to be number, which will prevent the user from ever even entering a non-number value.
When you have a ton of else if statements, it's better syntactically to use a switch case (some might argue against this, but in my opinion it's much easier to read).
I rarely see the <br> tag being used in modern web-applications. Use it sparingly, and opt for flex or grid instead to space out your items.
Don't use the == operator, instead, use the "strict equals" operator: ===
If you're checking for whether or not a condition is false, you don't have to do if (conditon === false). You can negate the condition with the ! operator: if (!condition). This will also fire if the condition returns a falsy value, such as '', 0, undefined, null, or NaN.
Most importantly, try to separate your logic into "Lego blocks". Basically, make small functions that do one thing. Debugging mega functions is not fun. We've implemented this functional logic in the example below by creating the validate function.
const textbox1 = document.querySelector('#text1');
const textbox2 = document.querySelector('#text2');
const pTag = document.querySelector('#P');
const actions = {
mul: 'mul',
sub: 'sub',
div: 'div',
add: 'add',
};
const validate = (num1, num2) => {
if (isNaN(num1) || isNaN(num2) || !Number.isInteger(num1 + num2)) return false;
return true;
};
const handleClick = ({ target }) => {
let answer;
const val1 = +textbox1.value;
const val2 = +textbox2.value;
if (!validate(val1, val2)) {
pTag.textContent = 'Invalid input! Much provide two integers.';
return;
}
switch (target.getAttribute('id')) {
case actions.add:
answer = val1 + val2;
break;
case actions.sub:
answer = val1 - val2;
break;
case actions.div:
answer = val1 / val2;
break;
case actions.mul:
answer = val1 * val2;
}
pTag.textContent = answer;
};
window.addEventListener('DOMContentLoaded', () => {
for (const action of Object.values(actions)) {
const elem = document.querySelector(`#${action}`);
elem.addEventListener('click', handleClick);
}
});
<body>
<input type="number" id="text1" placeholder="enter a value" />
<p id="zero"></p>
<input type="number" placeholder="enter a value" id="text2" />
<p id="P" style="color: red"></p>
<div style="display: flex; flex-direction: column; gap: 20px; max-width: 200px">
<button id="mul">Multiply</button>
<button id="sub">Subtract</button>
<button id="div">Divide</button>
<button id="add">Add</button>
</div>
</body>

Calculator shows syntax error and referenceError

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cost Calculator</title>
</head>
<body>
<h1>
College Cost Calculator
</h1>
<form>
<input type= "numbers" id= "annualCost" placholder= "annual cost" />
<br>
<input type= "numbers" id= "inflationRate" placholder= "inflationRate" />
<br>
<input type= "numbers" id= "yearsUntilCollege" placholder= "yearsUntilCollege" />
<input id= "button" type="button" value = "Estimate" onclick= "calculator()"/>
<input id= "reset" type="reset" value = "Reset"/>
</form>
<p id= "result">
</p>
<script>
// your code here
document.getElementById(button) = function calculator () {
let inflationRate = document.getElementById(inflationRate);
let annualCost = document.getElementById(annualCost);
let totalCost;
let annualSaving;
let yearsUntilCollege = document.getElementById(yearsUntilCollege);
totalCost = annualCost;
let amount = (inflationRate * annualCost) + annualCost;
totalCost += amount;
amount = ((inflationRate * 2) * annualCost) + annualCost;
totalCost += amount;
amount = ((inflationRate * 3) * annualCost) + annualCost;
totalCost += amount;
annualSaving = totalCost / 5;
return amount
return annualSaving
console.log(`For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`);
console.log(`You have to pay $${totalCost}.`);
console.log(`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`)
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
`You have to pay $${totalCost}.`
`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`
}
</script>
</body>
</html>
This is a code to calculate the college cost for Four(04) years including inflation and how much to save before college begins.
Help me figure out the issue with this code. It keeps giving syntax Error 28:15 and reference Error. I can't seem to figure out what I have done wrong and did I call the function correctly?
Many issues here:
1- Element IDs are strings. Therefore, document.getElementById expects you to pass a string to it, and strings are surrounded by quotation marks (' or ").
2- To get the value of <input> elements, you should use .value. So for example:
//get the value of input with id "inflationRate"
var inflationRate = document.getElementById("inflationRate").value;
3- To call a function on button click, use the button's onclick event, like so:
function calculator() {
//do something...
}
//call the function calculator whenever the button is clicked
document.getElementById("button").onclick = calculator;
4- As pointed out by #ecg8 in the comments, return statements jump out of the function immediately, and therefore you cannot have further statements/computations after the return statement, as they will not be reached.
And as a side note, in your HTML, numeric inputs should have a type of number and not numbers.
Edit: Also, in your last statement here:
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
`You have to pay $${totalCost}.`
`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`
To concatenate these three strings into one, either wrap the entire string (all the lines) into one pair of backticks (`), or use the + operator to concatenate the strings:
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
+ `You have to pay $${totalCost}.`
+ `You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`;
On a final note, all these issues are basic Javascript stuff, so I
would really recommend to study and understand the basics of
Javascript (syntax, functions, events, etc.) before solving problems
like this one.

Adding a score to every input field the user fills in the form and displaying it

Currently i have developed a program that gets the count of all the inputs field and adding up a percentage for the numbers of fields that are filled individually.
what i need now here, i need to assign a number to each input field and when the user fills an input field i need to show it to the user as a " SCORE ".
below is the program i have built.
<html>
<body>
<label> Name </label>
<input class="track"/>
<label> Name </label>
<input class="track"/>
<h5>Profile Strength <span class='perc'>0</span>%</h5>
</body>
</html>
and the JavaScript is
<script>
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
so when you fill the first input field the 'Profile strength' will show 50% as there are only 2 input fields, and when you fill the second input it will show 100%.
i want to show a number instead of a percentage here like
input 1 = 10
input 2 = 20
so when the user fills input 1 his "SCORE" will be 10,
and when the user fills the next input the total must add on and show 30 in real time.
sorry if have confused a few developers but this the only way i understood the assignment i got.
Try the following:
Html:
<html>
<body>
<label> Name </label>
<input class="track" data-score=10 />
<label> Name </label>
<input class="track" data-score=20 />
<h5>Profile Strength <span class='perc'>0</span>%</h5>
<h5>Score <span id="score">0</span></h5>
</body>
</html>
JS:
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var score = 0
$('input.track').each(function(){
var _score = $(this).data("score")
if ($(this).val().length > 0) {
score += _score
}
})
$('#score').text(score)
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
Or, a live version https://jsfiddle.net/wmt6cznh/2/
Is this what you want to achieve?

Comparing two hidden input with simple javascript failed

I got two hidden input HTML that I want to compare with javascript onclick submit button. But it won't work even though it seems simple and straightforward.
The function is:
function check() {
if ((parseFloat(document.getElementById("price_sell").value) < (parseFloat(document.getElementById("price").value)*0.95)) OR (parseFloat(document.getElementById("price_sell").value) > (parseFloat(document.getElementById("price").value)*1.05)) ){
alert("too high/low!");
}
}
And the input text is as follow:
<input type="hidden" id="price" name="price" value="<?php echo $prc ?>" />
<input type="hidden" id="price_sell" name="price_sell" />
I have check the hidden input value and even though the 'price_sell' is twice as big/small as the 'price', the alert won't fire. What is wrong with it?
Change the operator OR to ||.
This code, if was JS code, doesn't work because syntax error.
First as #Rakesh_Kumar mentioned set value to price_sell input field and try below code.
function check() {
var price_sell = parseFloat(document.getElementById("price_sell").value);
var price = parseFloat(document.getElementById("price").value);
if ( (price_sell < ( price *0.95 ) ) || (price_sell > (price*1.05) ) ) {
alert("too high/low!");
}
}
Storing the price_sell and price value in JS variables for better reading purpose . FYI there were some syntax error due missing brackets and usage of OR which i have replaced with ||.
You must change the OR by || and add a value to price_sell
Test with this example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="estilos/estilos.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Test</title>
<script type="text/javascript">
function check() {
var price_sell = parseFloat(document.getElementById("price_sell").value);
var price = parseFloat(document.getElementById("price").value);
if ((price_sell < (price * 0.95)) || (price_sell > (price * 1.05))) {
alert("too high/low!");
}
}
</script>
</head>
<body>
<input type="hidden" id="price" name="price" value="2" />
<input type="hidden" id="price_sell" name="price_sell" value="4"/>
<input type="button"
onclick="check()"
value="Check">
</body>
</html>
Use Number(variable) to convert text to number and then do your comparing maths.
Example:-
var price = Number(document.getElementById(price).value);
var price_sell = Number(document.getElementById(price_sell).value);
var compare = price_sell - price;
Or you can check the variable type, using typeof
If value is null or undefined then Number function will convert it to 0 (zero).
Even though the 'price_sell' is twice as big/small as the 'price'-
Updated Answer 2:
/*
Errors - price = '10 $'; means remove currency symbols
or characters from price_sell and price variable
Use trim() to remove whitespace.
I recheck my code, and found brackets missing, and posted again.
*/
price_sell = Number(price_sell.trim());
price = Number(price.trim());
if ((price_sell > (price/0.80)) && (price_sell < (price*1.30))) {
// good
} else {
// bad
}
Regards

javascript calculation field comparison algorithm

Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.

Categories