How to get Inifinite Values for textbox - javascript

how do I change that the user is able to key in the value from 0- infinite?
Because it only allows the user to key in from 0-9 at this moment.
function validate() {
var values = document.getElementById("digit").value;
if (/^[0-9]$/.test(values) == false) {
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero";
return false;
}
return true;
}

Use typeof and the urnary operator + to check if its an number and greater equal then 0
function validate() {
var value = document.getElementById("digit").value;
if (!(!isNaN(+value) && value >= 0)) {
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero";
return false;
}
document.getElementById("numbers").innerHTML = "";
return true;
}
<input onkeyup="validate()" value="" id="digit" />
<p id="numbers"></p>

Your Regular expression is looking for one and only one digit between the start and end of the string.
Try /^[0-9]$+/.
The + means 'At least one, up to an infinity of' whatever it's stuck too.

Use the native method Number.isInteger() to check if the last character is a number. If not, slice it.
function validate(el) {
var lastChar = Number(el.value.slice(-1));
if (!Number.isInteger(lastChar)) {
el.value = el.value.substring(0, el.value.length - 1);
};
}
<input type="text" oninput="validate(this)">

Related

Find the output using typeof function

I am writing a code. And here I have a problem how can I fix that. I have an input line, it takes a string or a number. So I need to check what is the output and get the answer. I need to give a simple solution. So I can't use functions or something like that.
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}
prompt will always return a string.
If you want to check whether the string is composed purely of numerical values, you could use a regular expression:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
If you don't want to use a regex, you can use Number alone, but then you'll also include values like Infinity which might not be desirable, and since Number('') gives 0, you'll have to check for that separately:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
Another approach that I'd recommend is to avoid prompt entirely. Consider using a proper modal instead, such as a form with an input box and a submit button.
In such a case, if you want to require a numeric input, just do:
<input type="number">
I had a similar problem a few weeks ago and this is what I did:
function testNumber(test) {
if (isNaN(test) === false) {
console.log("this is a number");
} else {
console.log("this is not a number");
}
}
testNumber(4); // number
testNumber("4") // number
testNumber("string") // not a number
You can replace "test" for a variable if you don't want to use a function
if (isNaN(myVar) === false) {}
And you may want to add more checks if you want to differentiate between 4 and "4"
You can do
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
So it can change all Stringed-numbers to numbers and check if they are number with the isNaN function

Difficulty recognizing data type at validation time

I want to validate, but when I enter a number or a string in any case, the data type shows me a string and I can not validate correctly, please help me
function Validator() {
const x = document.getElementById("fname").value;
const a = typeof x === "string" && x.length >= 1;
console.log(typeof x);
if (a) {
console.log("type string");
} else {
console.log("other type");
};
}
<input id="fname">
<input type="submit" onclick="Validator()">
Values from input fiedls are only Strings. So you have to parse it.
const x = document.getElementById("fname").value;
if (x.length >= 1) {
if (Number.isNaN(x) == false) {
console.log("Numeric type");
//Using parse methods for different numbers)
} else if (x.length>0) {
console.log("String type");
}
}
For more details: https://www.w3schools.com/jsref/jsref_isnan.asp
You can do it like this, use the Number.isNaN() function to check if something is not a number. Pass parseInt(x) to Number.isNaN(), which will try and convert x to a number. If it cannot convert it, it will return NaN.
function Validator() {
const x = document.getElementById("fname").value;
const isNaN = Number.isNaN(parseInt(x));
if (isNaN) {
console.log("type string");
} else {
console.log("number type");
};
}
<input id="fname">
<input type="submit" onclick="Validator()">
The value of an input is always a string. For example, when you enter 1, the actual value is not number 3, its the string "3". You can use isNan() function as stated in above examples.
Read more on validating numbers in this post - (Built-in) way in JavaScript to check if a string is a valid number

How to check if there is a number in prompt because all things are string in prompt?

let b=prompt("");
If in prompt someone enter 4 this will also come as a string, so how will I find that it is a number and not a string.
You can use either isNaN to check whether the input is a number or not
// let a = prompt()
let a = "a"
const isNumber = (num) => !isNaN(parseInt(a))
console.log(isNumber(a))
a = "2";
console.log(isNumber(a))
Please have a look at this:
function isNumber(number) {
return Number.isInteger(number) || !isNaN(parseFloat(number)) && isFinite(number)
}
var result = prompt("Enter your number");
if (!isNumber(result)) {
console.log("This is not a number, Try Entering another.");
}
else {
console.log("This is a number.");
}
First Approach: Use !isNaN()
isNaN(x) returns true if x is not a number so invert it using ! to get true whenever x is a number.
Second Approach: use typecasting
Number(x) will convert str to number and return the number and if x is not a number it will return NaN
b = prompt("")
return !isNaN(b)
This will return true if it is a number

how to check a html form input is an integer or not

<script>
var y = document.getElementById("quantity").value;
alert(y);
if (Number.isInteger(y)) {
} else {
document.getElementById("quantity").style.borderColor = "#e60000";
document.getElementById("qty").innerHTML = " enter valid quantity.*";
document.getElementById("quantity").focus();
}
</script>
I need to validate a quantity field in a HTML form. but when I put any value in quantity like number, text or whatever, program always run in else part of this code. it's not working for an integer.
There are multiple ways of achieving the same. Some of them are mentioned below:
Use Pattern <input type="text" pattern="^[0-9]*$" />
Use Number field <input type="number" min=0 max=100 step=1>
Use isNan to verify if input is a number isNaN(y) and also verify if integer by using y.indexof(".")==-1
Assuming you have a textbox input for the quantity, the value of that textbox will always be a string. Check using isNaN:
var y = document.getElementById("quantity").value;
if (!isNaN(y)) {
console.log('is a number');
} else {
document.getElementById("quantity").style.borderColor = "#e60000";
document.getElementById("qty").innerHTML = " enter valid quantity.*";
document.getElementById("quantity").focus();
}
isNaN returns whether the given value is Not a Number. So, if it goes into the if block, you know that the string is a number. You can then convert it to real integer using parseInt function.
convert given value to the number using Number
now check with isNaN method .
const quantity = document.getElementById("quantity");
const qty = document.getElementById("qty");
let y = quantity.value;
let numberY = Number(y);
if(isNaN(numberY)) {
console.log('This is not a number');
} else {
console.log('do it now. it is a number');
quantity.style.borderColor = "#e60000";
qty.innerHTML = " enter valid quantity.*";
quantity.focus();
}
Try this one,
<script>
var y = document.getElementById("quantity").value;
if (!isNaN( parseInt(y) ) ) {
} else {
document.getElementById("quantity").style.borderColor = "#e60000";
document.getElementById("qty").innerHTML = " enter valid quantity.*";
document.getElementById("quantity").focus();
}
</script>
Maybe just compare it with a number
if(y != "" && y - y == 0) { }

If condition for comparing integer and float does not working

I am using one If condition in javascript ,
var iid = "c_poqty_"+itemid;
var calculatedQuantity = document.getElementById(iid).value;
if(! isNaN(actualQuantity)) {
if(actualQuantity >= calculatedQuantity) {
return true;
} else {
alert("You must enter the order qty same or greater than the calculated PO Qty");
document.getElementById(iid).focus();
return false;
}
} else {
alert("Please Enter valid number");
document.getElementById(iid).focus();
return false;
}
Here, calculatedQuantity is always in float and while actualQuantity can be integer,
I have one testcase:
calculatedQuantity = 1.0
actualQuantity = 1
Appreciate for your help!
Actually, I suspect they're both strings. Certainly calculatedQty is, as you've retrieved it from the value of an input field, and the value property's value is always a string. Use parseInt and/or parseFloat so you're comparing numbers rather than strings.
Consider:
console.log("1.0" > "1"); // "true"
console.log(1.0 > 1); // "false"

Categories

Resources