Multiplying in javascript with textbox - javascript

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>

Related

Im learning JS and i have a task to make the numbers that i input reverse and pop up in an alert

i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>

Javascript : multiple remainder pricing table

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])) )

Prevent Wrong Input in JS After Submitting A Form

I am creating a sample MabLibs type thing in HTML and JS. When the person inputs stuff in a field, it will use that to create their own MadLib.
I've done a little research and not finding exactly what I am looking for. Say a person puts 12 in the Name field. How would code that so if this instance does happen, it won't go through and alert "That is not a valid input. PLease type again!" or something along those lines.
The code I am using is below. I am very new to Javascript so I know the format and stuff might be wrong.
<html><head>
<title>
Mad Libs Story
</title>
<script>
function getVars() {
person1 = String(document.getElementById("personOne").value);
age = Number(document.getElementById("ageOne").value);
firstAdjective = String(document.getElementById("adjective").value);
document.getElementById("madLibCreation").innerHTML = "There once was a person named " + person1 + ". She was " + age + " and very " + firstAdjective = ".";
}
</script>
</head>
<body>
<h3>
Welcome to Mad Libs! Please type in the prompted Information. Then press the submit button. Have fun!
</h3>
<p>
Name of Person in Room: <input type="text" id="personOne">
</p>
<p>
Age: <input type="text" id="ageOne">
</p>
<p>
Adjective: <input type="text" id="adjective">
</p>
<input type="submit" value="Get My MadLib Creation!" onclick="getVars();">
<p id="madLibCreation"></p>
</body></html>
For that, you have to check Name field value is number or not. We can check the value is number or not using isNaN function. This function returns true or false.
isNaN(12) // falsee
isNaN(-4.5) // false
isNaN(15-3) // false
isNaN(0) // false
isNaN('123') // false
isNaN('Nuwan') // true
isNaN('2005/12/12') // true
isNaN() // true
So, in your code getVars() function change like this
function getVars() {
var name = document.getElementById("personOne").value;
if(!isNaN(name) && name.length != 0){
alert("That is not a valid input. PLease type again!");
}else{
person1 = String(document.getElementById("personOne").value);
age = Number(document.getElementById("ageOne").value);
firstAdjective = String(document.getElementById("adjective").value);
document.getElementById("madLibCreation").innerHTML = "There once was a person named " + person1 + ". She was " + age + " and very " + firstAdjective + ".";
}
}
https://www.w3.org/WAI/tutorials/forms/validation/
This link provides some useful information and example code around how you can do this with HTML5, providing the validations and required inputs to each input field.
By implementing these validations your form will not submit until the requirements are met.
Here are a few other ideas that may also help:
By using a
<form onsubmit="getVars()" name="MadLibs">
tag, your data will be wrapped inside the event, which can be accessed within your submit function. This will also reduce the effort to collect the data via element id’s.
const getVars = function(event) {
event.preventDefault(); // stop the page refresh on submit
const formData = event.target;
const personOne = formData.personOne;
...
}
Lastly by adding tags for each input, it will further increase the accessibility of the form:
https://www.w3.org/WAI/tutorials/forms/labels/
Hope this helps with your project.
So you want to prevent wrong information before submitting any thing. This can be achieved by some checks to the value entered into the fields. This can be done all at once on button click or while typing with an event handler on the field for keyup. You can further use setTimeout to check with a small delay.
If you check and set classes to elements which are faulty, you can check for them with a css selector.
const person1 = document.getElementById("personOne")
const age = document.getElementById("ageOne")
const firstAdjective = document.getElementById("adjective")
// use a function(){} block for the handler, it will bin this
person1.addEventListener(`keyup`, function(){
// use arrow function to not bind this so it will refer to the html node
// can be used to delay the evaluation
setTimeout(()=>{
// some regex... /regex/flags will create a new regex
// ^ is start, $ is end and [a-z]* is a to z 0 or more times
// flag i is case insensitive
const regEx = /^[a-z]+$/i
//
if(!regEx.test(person1.value)){
this.classList.add(`invalid`)
} else {
this.classList.remove(`invalid`)
}
},200)
})
function getVars() {
if(!document.querySelectorAll(`.invalid`)[0]){
document.getElementById("madLibCreation").innerText = `There once was a person named ${person1.value} she was ${age.value} and very ${firstAdjective.value}.`
} else {
alert(`fix your shit`)
}
}
.invalid{
color: red;
}
<html>
<head>
<title>
Mad Libs Story
</title>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='main.css'>
</head>
<body>
<h3>
Welcome to Mad Libs! Please type in the prompted Information. Then press the submit button. Have fun!
</h3>
<p>
Name of Person in Room: <input type="text" id="personOne">
</p>
<p>
Age: <input type="text" id="ageOne">
</p>
<p>
Adjective: <input type="text" id="adjective">
</p>
<input type="submit" value="Get My MadLib Creation!" onclick="getVars()">
<p id="madLibCreation"></p>
</body>
<script src="./main.js"></script>
</html>

str.replace(/[^0-9]/g, " ") erases my whole string instead of just getting rid of non-numerical characters. How to make it work properly?

I'm trying to use str.replace in order to remove any non-numerical characters from a number imput field when someone uses copy-pastes something in it. However the function always seems to remove all characters instead of just removing the non-numerical ones.
Surprisingly the function is able to detect when my string is purely numerical and won't change it in those cases, but adding a single other character will cause the whole string to be ditched instead of just removing the wrong characters.
I tried to change the regexp of the function to /\D/, but it didn't amount much.
Here's a minimal reproducible example, which must be run on Firefox.
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body style="margin:0px;">
<script src="../lib/jquery-3.3.1.js"></script>
<input type="number" id="inp"></input>
<script>
let input = document.getElementById("inp");
input.onblur = function()
{
$(document).ready(function()
{
input.value = input.value.replace(/[^0-9]/g, "");
});
}
</script>
</body>
</html>
I expect an output such as "34a01 2" to be "34012", but the actual output is "" (nothing). Is there something wrong in my regexp ?
let input = document.getElementById("inp");
input.onblur = function() {
$(document).ready(function() {
input.value = input.value.replace(/[^0-9]/g, "");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="inp"></input>
This looks to be a Firefox issue (or bug). Whenever a numeric input has non-numeric characters anywhere, the .value of the field will be the empty string:
setInterval(() => {
console.log(input.value);
}, 400);
<input id="input" type="number">
It's unfortunate, but you may have to simply remove the type="number" for the .value to be retrieved and replaced as desired:
let input = document.getElementById("inp");
input.onblur = function() {
input.value = input.value.replace(/[^0-9]/g, "");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inp"></input>
Either that, or keep type="number" and tell the user that the value they attempted to paste is invalid, and prevent it (because you have no way of retrieving and replacing it).
(also: only call $(document).ready once, when you're adding the listeners, if at all - your current code is adding a new listener every time the field is blurred)
I've read your comments about Firefox and I've prepared a new version.
Not including the "number" type seems to work.
Using "number" type is not causing any issue in Chrome so I guess that Firefox is not behaving in the same way.
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body style="margin:0px;">
<script
src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8="
crossorigin="anonymous"></script>
<input id="inp"></input>
<script>
let input = document.getElementById("inp");
input.onblur = function() {
input.value = input.value.replace(/[^0-9]+/g, "");
}
</script>
</body>
</html>

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

Categories