Comparing two hidden input with simple javascript failed - javascript

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

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>

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>

Why does "greater than" comparison of numbers give unexpected result

There is an input field, like this,
<input class="form-control" type="number" name="recieved_by_quantity" id="quantity" />
Dynamically, a value is assigned to the input tag, like this,
document.getElementById('quantity').value = qu; //var qu=11 lets say
Now, what i want is, if the user manually inputs a value greater than "qu", then the value would automatically change itself to "qu".
What i did for this is something like,
document.getElementById('quantity').addEventListener("change", function() {
var qc = this.value;
if(qc>qu) {
this.value = qu;
}
});
The strange thing that is happening is if i input any value from 2 to infinity, it is changing all of them to 11. Only value it does not change are 0,1,10,100,1000,10000 and so on..
I am completely confused. Please help.
Its simple, use parseInt to get actual number value of your text-area.
You are getting string by default.
this.value is giving you '11'
parseInt(this.value) is giving you 11.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<input class="form-control" type="number" name="recieved_by_quantity" id="quantity" />
</body>
<script>
var qu = 11;
document.getElementById('quantity').value = qu;
document.getElementById('quantity').addEventListener("change", function() {
var qc = parseInt(this.value);
if(qc>qu) {
this.value = qu;
}
});
</script>
</html>
Use parseInt
var qc = parseInt(this.value)

trying to checking a value within in a form is a number in a set range

Trying to write a script that will check the value in the form is a number between the range of 1 to 99999.
1) The script work mostly except for two things if you put a number then letter it won’t detect that you entered letters as well as numbers
2) I want it to run the script on onblur event, however every time I try the script does not work at all.
Did study java years and year ago and found I forgotten most things if people can point out where I am going wrong would be very greatful
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Please enter your age</title>
<script language="JavaScript1.2">
function checknumber(){
var x=document.checknum.pnum.value
/*does it contain non digits */
var anum=/(^\D+$)|(^\D+\.\D+$)/
if (anum.test(x))
{
alert("Please input a valid Runner ID between 1 to 99999 !")
testresult=false
}
/*is it above 99999*/
else if (x > 99999)
{
alert("Please input a valid Runner ID between 1 to 99999 !")
testresult=false
}
/*is it below 1*/
else if (x < 1)
{
alert("Please input a valid Runner ID between 1 to 99999 !")
testresult=false
}
return (testresult)
}
</script>
</head>
<body>
<form name="checknum" onSubmit="return checknumber()">
Please input a valid Runner ID between 1 to 99999:
<input type="text" name="pnum" onchange="checknumber()">
<input type="submit" value="Submit">
</form>
</body>
</html>
Many Thanks
Damien
Import Jquery Library and use this function
<script type="text/javascript">
$(document).ready(function(){
$("#pnum").keypress(function (e)
{
//if the letter is not digit then display error and don't type anything
if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
{
return false;
}
});
});
but id for the textbox
<input type="text" name="pnum" id="pnum" maxLength="5" >
this will ensure that you can add numbers only and 5 char

Radio Button producing undefined value in javascript function

I am trying to send the value of a radio button to a javascript function. Eventually the function will do more but my testing it has come to a dead end because I keep getting a returned value of undefined. Here is what I have:
<!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>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<SCRIPT TYPE="text/javascript">
<!--
function jobWindow(){
var target;
for( i = 0; i < document.jobView.sales.length; i++ ){
if( document.jobView.sales[i].checked == true )
target = document.jobView.sales[i].value;
break;
}
alert( "val = " + target );
//var load = window.open('target','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
}
// -->
</script>
</head>
<body>
<form name="jobView">
<input name ="sales" value="all" type="radio" />All
<input name="sales" value="darell" type="radio" />Darell
<input name="sales" value="kevin" type="radio" />Kevin
<input name="sales" value="brad" type="radio" />Brad
<input name="sales" value="chongo" type="radio" />Chongo
<input type="button" value="View Records" onclick="jobWindow()"/>
<input type="button" value="View Calendar" />
</form>
</body>
</html>
The access path you actually want is:
var el = document.forms["jobView"].elements["sales"];
The straight dot chain (document.jobView.sales) makes an implicit call to the "all" collection, which will only work in IE. (Yes, I know that Firefox returns an identical-looking string in its error console when things go wrong, but you can't actually use it in your own code.) getELementsByTagName() and getElementsByName() will work just fine, but then you need to ensure that the elements in the returned collection are the ones you actually want. (Assume that a time will come when you want to create more than one form on the page, and that field names will collide. It will never happen, of course, unless you fail to make that assumption out of the gate, whereupon another developer will immediately add a second form to the page you just committed.)
Try with document.getElementsByTagName like this:
function jobWindow(){
var myvalue;
var el = document.getElementsByTagName('input');
for( i = 0; i < el.length; i++ ){
if (document.forms['jobView'].el[i].type === 'radio' && document.forms['jobView'].el[i].name === 'sales')
{
if(document.forms['jobView'].el[i].checked == true )
{
myvalue = document.forms['jobView'].el[i].value;
break;
}
}
}
alert( "val = " + myvalue );
}
Note also that your break line never executed because you were missing curly brackets:
if( document.jobView.sales[i].checked == true )
{
target = document.jobView.sales[i].value;
break;
}
change document.jobView.sales to document.getElementsByName('sales')
throw some debugging in there. for example put an alert() inside the for() statement to make sure it is getting a definition for document.jobView.sales.length.
If it doesn't make the alert, you can almost bet document.jobView.sales.length is undefined.
You can then do try { var length = document.jobView.sales.length; } catch(e) { alert(e); } to verify this.
If you verify that document.jobView.sales.length isn't being defined, you may have to use document.getElementsByTagName, and loop through them instead of document.jobView

Categories