Check for number within a url using javascript? - javascript

I've a gallery within a website and each gallery image is represented by a url like so:
http://www.example.com/gallery/my-photos#10
http://www.example.com/gallery/my-photos#11
http://www.example.com/gallery/my-photos#12
.
.
.
.
.
I've created a conditional statement to prevent user from invalid url.
var galleryNum = window.location.hash.substring(1);
if( typeof(galleryNum) == "string" || typeof(galleryNum) == "NaN" ){
console.log('this is not a number');
}else if(typeof(galleryNum) == "number"){
console.log('this is a number');
}
However this doesn't work, the value I get from window.location.hash.substring(1) will always be a string regardless I enter number or a string.

if you want to get number, you should use:
parseInt(galleryNum,10)
if you want to check whether galleryNum is number or not, you can use:
isNaN(parseInt(galleryNum,10))

Try utilizing .test()
if( /\d/.test(galleryNum) ) {
// `Number`
} else {
// not `Number`
}

there is no "NaN" type. In fact, despite NaN standing for Not-a-Number, it actually is a number: typeof NaN === 'number'
You can however use isNaN() to test for NaN.
To test if the string returned from the URL can be cast to a number, use parseInt:
var galleryNum = parseInt(window.location.hash.substring(1),10);
if (typeof(galleryNum) === 'number' && !isNan(galleryNum)) {
// got a number here
}

Related

How do I check if a variable is null, so that I can change it later on?

A group of me and two other people are working to make a Jeopardy game (themed around United States History questions) all in JavaScript. For our final Jeopardy screen, the two teams will each bet a certain amount of money. To prevent a team from typing in random letters for a bet (i.e typing in "hasdfhgasf" instead of an actual amount), we're trying to write an 'onEvent' command that checks to see if a bet is null. If that bet is null, then the code should come up with a message on the screen that tells them to check their bets again.
We tried using statements like, if "null" or if " " but neither of these statements works. We've worked with using getNumber and getText commands, along with just regular variable comparisons with or booleans. So far, we haven't had any luck with these methods.
Here's the group of code we're having issues with:
onEvent("finalJeopardyBetSubmit", "click", function() {
team1Bet = getNumber("team1BetInput");
team2Bet = getNumber("team2BetInput");
console.log(team1Bet);
console.log(team2Bet);
if (getText("team1BetInput") == "" || getText("team2BetInput") == "") {
console.log("Check bet!");
finalJeopardyError();
} else if ((getText("team1BetInput") != 0 || getText("team2BetInput") != 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") < 0 || getNumber("team2BetInput") < 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") > team1Money || getNumber("team2BetInput") > team2Money)) {
console.log("Check bet!");
finalJeopardyError();
} else {
console.log("Done");
}
});
You can also check out the whole program on Code.org if you'd like to get a better look.
We expect that with the console.log commands, it should say "check bet" if the bets return as null. Instead, the code has ended up fine, and not displaying our error message, even if we type in nothing or just random letters.
a null variable will evaluate to false. Try:
if(variable){
// variable not null
}else{
// variable null
}
Convert the value to a Number first using Number(value) and then check for falsy values using the logical not ! operator. If they enter alphabetic characters, then calling Number('abc') results in NaN.
If a value can be converted to true, the value is so-called truthy. If
a value can be converted to false, the value is so-called falsy.
Examples of expressions that can be converted to false are:
null; NaN; 0; empty string ("" or '' or ``); undefined.
The ! will change any of the falsy values above to true, so you can check for all of them with just the first if statement below.
onEvent("finalJeopardyBetSubmit", "click", function() {
// Convert these values to numbers first
var team1Bet = Number(getNumber("team1BetInput"));
var team2Bet = Number(getNumber("team2BetInput"));
if (!team1Bet || !team2Bet) {
// Handle invalid number error
}
else if (team1Bet < 0 || team2Bet < 0) {
// Handle invalid range error
}
else if (team1Bet > team1Money || team2Bet > team2Money) {
// Handle insufficient funds error
}
else {
// Finish game
}
})
You can read more about the logical operators here.

Checking input type in JS

I'm using the typeof command to make sure that only 1 of the 2 input fields of this temperature (Celsius to/from Fahrenheit) calculator is populated with data and it has to be a number. If the input is not a valid number or both fields are populated, the app will throw an error message.
The problem: nothing satisfies this condition - the errorMessage is always shown, even if I type in a valid number.
Is typeof the right solution to this problem? If it is, why is this code not working?
document.getElementById('temperature-form').addEventListener('submit', calculateResult);
function calculateResult(e) {
e.preventDefault();
const celsiusInput = document.getElementById('celsius');
const fahrenheitInput = document.getElementById('fahrenheit');
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if ((typeof celsiusInput === 'number') && (fahrenheitInput === null)) {
resultOutput.value = (celsiusInput.value * 1.8 + 32) + ' Fahrenheit';
} else if ((celsiusInput === null) && (typeof fahrenheitInput === 'number')) {
resultOutput.value = ((fahrenheitInput.value - 32)/1.8) + ' Celsius';
} else {
errorMessage('Please add a number in one of these fields');
}
}
Many thanks!
You could check the value properties of each input to see if they are numbers using the isNaN() function like so:
function calculateResult(e) {
e.preventDefault();
//Get the value of each input box
const celsiusValue = document.getElementById('celsius').value;
const fahrenheitValue = document.getElementById('fahrenheit').value;
//Get the result element
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if(!isNaN(celsiusValue) && (fahrenheitValue === null || fahrenheitValue === "")){
//Only celsiusValue has a valid number
resultOutput.value = (celsiusValue * 1.8 + 32) + ' Fahrenheit';
}else if(!isNaN(fahrenheitValue ) && (celsiusValue === null || celsiusValue === "")){
//Only fahrenheitValue has a valid number
resultOutput.value = ((fahrenheitValue - 32)/1.8) + ' Celsius';
}else if(!isNan(celsiusValue) && !isNan(fahrenheitValue )){
//Both contain a valid number
//Figure this one out as you didn't account for it
}else{
//Neither is a valid number
errorMessage('Please add a number in one of these fields');
}
}
Documentation of isNaN():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
When doing const celsiusInput = document.getElementById('celsius') you're getting the DOM Element, not the value.
In order to obtain de value you'd have to check for the property value.
So you'd end up with something like this:
const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
Now if we do typeof celsiusValue we'll always get string, because text/number inputs always accept text (check input's type property for more info).
The proper way to check if there are numbers or letters is using Regular Expressions.
I'll leave a simple example to act as a starting point for you:
const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
if(/\D/.test(celsiusValue)) {
alert("There is something that's not a number in the Celsius input!")
}
First of by doing a comparison like this fahrenheitInput === null you're comparing a DOM element against the value null.
That will only evaluate to true if the DOM Element never existed.
Secondly the typeof method will always evaluate to a String on DOM element types, so again this will always be false.
To really get what you want you have to do a proper check
To check if both input fields are supplied, simply checking the length of the values will surface:
if(fahrenheitInput.length > 0 && celsiusInput.length > 0) //fail
If fahrenheitInput only is given:
if(!isNaN(Number(fahrenheitInput)) //convert
if celsiusInput only is given:
if(!isNaN(Number(celsiusInput)) //convert
Finally if all checks above don't check our, fail

typeof command doesnt work

Hi I'm trying to check the value of DOM with:
if ($('#ATTN').val() == '') {
$('#ATTN').val(0);
} else {
iattn=$('#ATTN').val();
alert(iattn);
if(typeof iattn == 'number'){
alert('oh');
}
}
but it returns nothing. Also no error shown.
This line
iattn=$('#ATTN').val();
Returns a string.
If you want to see whether it can be converted to an integer, then what you want is this:
iattn=parseInt($('#ATTN').val());
if (iattn) {
alert("oh");
}
Use parseFloat rather than parseInt if you want a more general number test.
If you want to check that the result of parsing matches the input, use something like this:
iattn=$('#ATTN').val();
if (iattn == parseInt(iattn)) {
alert("oh");
}
A simpler check, which won't actually convert anything to a number, and will allow all number formats (eg 2.3, 0x3, +23) is this:
if (!isNaN(iattn)) {
alert("oh");
}
Credit to #p.s.w.g from a comment.
.val() return a DOMString(string)
so typeof iattn always will be a string
if you want the typeof number you need convert to int
using parseInt(iattn) or parseFloat(iattn)

How to add msg to a variable that is undefined?

Hopefully I am asking the correct question. I want to add a msg that states "Please Enter Item weight" if the user clicks the button without inputting anything in the text field.
I tried multiple ways but can't seem to get it. A msg comes up saying "undefined" instead of what I want it to say/show.
if( typeof(weight) == 'undefined' || weight == null) {
msg = "<div id='error'>Please Enter Item Weight</div>";
}
You need to change weight definition to something like this:
var weight = parseInt(document.getElementById("weight").value || 0);
When you try to convert a string to a number using parseInt it will return NaN if you pass empty string (when there is no user input). So in this case simple fallback to 0 value || 0 can fix it.
Another option is to use + operator to cast to a number:
var weight = +document.getElementById("weight").value;
Demo: http://jsfiddle.net/AvjS5/1/
if( weight == 'undefined' || weight == null) {
msg = "<div id='error'>Please Enter Item Weight</div>";
}
What you might want to do is, use the isNaN function. When you try to do a parseInt on an invalid string, the value returned is NaN a.k.a Not a Number.
var weight = parseInt( document.getElementById("weight").value );
if(isNaN(weight)){
msg="<div>Hello</div>"
}
Fiddle here
Also, you haven't added logic to see if none of the option buttons were checked.

Checking only the integer values through Regex

My Code:
I tried the following code
<SCRIPT type="text/javascript">
var num = "10";
var expRegex = /^\d+$/;
if(expRegex.test(num))
{
alert('Integer');
}
else
{
alert('Not an Integer');
}
</SCRIPT>
I am getting the result as Integer. Actually I declared the num varibale with double quotes. Obviously it is considered as a string. Actually I need to get the result as Not an Integer. How to change the RegEx so that I can get the expected result.
In this case, it should give the result as Not an Integer. But I am getting as Integer.
if(typeof num === "number" &&
Math.floor(num) === num)
alert('Integer');
else
alert('Not an Integer');
Regular expressions are there to work on strings. So if you tried it with something else than a string the string would either be converted or you would get an error. And yours returns true, because obviously the string only contains digit characters (and that is what you are checking for).
Use the typeof operator instead. But JavaScript doesn't have dedicated types for int and float. So you have to do the integer check yourself. If floor doesn't change the value, then you have an integer.
There is one more caveat. Infinity is a number and calling Math.floor() on it will result in Infinity again, so you get a false positive there. You can change that like this:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(num) === num)
...
Seeing your regex you might want to accept only positive integers:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(Math.abs(num)) === num)
...
RegExp is for strings. You can check for typeof num == 'number' but you will need to perform multiple checks for floats etc. You can also use a small bitwise operator to check for integers:
function isInt(num) {
num = Math.abs(num); // if you want to allow negative (thx buettner)
return num >>> 0 == num;
}
isInt(10.1) // false
isInt("10") // false
isInt(10) // true
I think it's easier to use isNaN().
if(!isNaN(num))
{
alert('Integer !');
}
else
{
alert('Not an Integer !');
}
Léon

Categories