I'm having trouble getting the Codecademy section of ifNan done. How do I make it so the ifNan function checks the number I manually input at the end when I run the function. For example:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else if (isNan(number)) {
return "Your input is not a number!";
} else {
return false;
}
};
isEven(2);
What would I put in the isNan function so that when I input the number at the bottom it also checks if it is actually a number?
you could condense that down to:
function isEven(number)
{
if(!isNaN(number) || number % 2 === 0)
{
return true;
}
return false;
}
See elclanrs comment. isNan is not a function isNaN is. caps matter there.
So...update to this long-standing issue:
I went back to codecademy and restarted the lesson. After researching for about a week, and a good long breather, I came back to this frustrating issue and even then found myself writing the same exact code that I had in the beginning of this issue (because I knew it was correct).
You all made valid points.
Dennis you're absolutely right this can be condensed in a few areas but Codecademy is very rigid (which I'm liking less and less) so it would have never let me pass the dang section.
Anyways, I wanted to close this but "answer" (kind of) it first.
Thanks for all your assistance.
Try this:
var isEven = function(number) { if (number % 2 === 0) { return true; } else if(isNaN(number) === true || false){ return "your input is not a number"; } else { return false; }// Your code goes here!
}; isEven("Gbemi")
Related
I wrote a simple code in javascript that was supposed to validate the length of a phone number inputed in an html form (check if it consists of 10 digits- as it is in my country).
So here's the function:
function check_tel(){
var tel=document.LpData.phone.value;
var i=0;
for(;i<10;i++){
tel/=10;
if(tel==0){
alert("unvaild phone number- too short");
return false;
}
}
if(tel>0){
alert("unvaild phone number- too long");
return false;
}
return true;
}
But it always outputs that the number is too long (i>10).
I already checked the value of "tel" variable before it enters the loop and everything is right.
I also tried it with a "while" instead of "for" loop.
So I concluded it's because of the "/" operator which doesn't work (although I still don't understand how it's possible) or it has something to do with the type of tel...
So what is the problem and how to fix it?
Thanks in advance!
Every input value is always a string. Using the divide operator on a string is not what you wanted. So you may convert the phonenumber to an int:
function check_tel(){
var tel=parseInt(document.LpData.phone.value,10)||0;
for(var i=0;i<10;i++){
tel/=10;
if(tel<1){
alert("unvaild phone number- too short");
return false;
}
}
tel/=10;
if(tel>1){
alert("unvaild phone number- too long");
return false;
}
return true;
}
also note that 123456789/10000000 is not 0...
and by the way, it is much easier to simply check for tel.length...
The best practice to do these things is to use a Regular Expression(Regex).
/^\d{10}$/ is a JS regex to check if the number is a 10 digit number.
function check_tel()
{
var tel = document.LpData.phone.value;
var teleRegex =/^\d{10}$/;
if(!teleRegex.test(tel)){
alert("invalid phone number")
}
else{
//do your thing
}
}
Possible work-around is
function check_tel()
{
var tel=document.LpData.phone.value;
if(tell.length == 0 || tell.length > 10){
alert("invalid phone number");
return false;
}
return true;
}
Try var tel = parseInt(document.LpData.phone.value); instead of var tel = document.LpData.phone.value;
I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.
I need to create a code in HTML/Javascript that will allow a user to enter an answer to a maths question and then the site needs to validate whether that answer is correct.
Been playing around for a few hours and researched the web but not found anything close.
Any help is appreciated!!
You could use javascript for validation,
Look at this example.
var value = Number(intfield.value);
if (Math.floor(value) == value) {
// value is an integer, do something based on that
} else {
// value is not an integer, show some validation error
}
checking if value of a textfield is integer in javascript
Javascript validation
function isInteger(number) {
var getVal = parseInt(number);
if (number.length == 0 || getVal == Number.NaN || getVal <= 0) {
return false;
}
return true;
}
Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.
here's my code that i try
function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
if(isNaN(pass.charAt(i))==false)
{
return true;
break;
}
else
{
return false;
}
}
}
i have tried that way but i fail, can u help me guys? thanks before
One possible approach:
function validateIn() {
var pass = document.getElementById('password').value,
p = pass.length,
ch = '';
while (p--) {
ch = pass.charAt(p);
if (ch >= '0' && ch <= '9') {
return true; // we have found a digit here
}
}
return false; // the loop is done, yet we didn't find any digit
}
The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.
Note that I have gone without isNaN, as it's a bit inefficient: the only thing required is a range check.
<script ="javscript"/>
function checkQuantity()
{
function noCharge(intQuantity){
if (intQuantity > 100) {
return true;
}
if (intQuantity < 100) {
return false;
}
return true;
}
checkQuantity=parseInt(prompt("Please enter the quantity of light bulbs",""))
if ((intQuantity)==true)
{
alert("Your light bulbs will arrive shortly. There is NO delivery charge")
}
else if ((intQuantity)==false)
{
alert("Your light bulbs will arrive shortly. There will be a delivery charge of £5.99")
}
else
{
alert("Please enter an amount")
}
}
</script>
Your code had some bugs.
Check this live example
function checkQuantity() {
function noCharge(intQuantity) {
if (intQuantity > 100) {
return true;
}
if (intQuantity < 100) {
return false;
}
return true;
}
var amount = noCharge(parseInt(prompt("Please enter the quantity of light bulbs", "")));
if (amount == true) {
alert("Your light bulbs will arrive shortly. There is NO delivery charge")
}
else if (amount == false) {
alert("Your light bulbs will arrive shortly. There will be a delivery charge of £5.99")
}
else {
alert("Please enter an amount")
}
}
checkQuantity();
Two obvious problems (well, two things collaborating to cause the same bug):
You're never calling noCharge. Rather than if ((intQuantity) == true), you should be saying if (noCharge(intQuantity) == true) (or, better, if (noCharge(intQuantity))...see below).
(intQuantity) will be truthy as long as it's not false, null, undefined, or 0. In your case, that's the vast majority of the time.
And a couple of style notes:
If you're returning a boolean, you don't really have to compare it to anything. Instead of saying if (noCharge(intQuantity) == true, you could just say if (noCharge(intQuantity)). To see if something's false, use the ! operator, like if (!noCharge(intQuantity)).
You also don't have to compare twice. A boolean is either true or false. The else if... part could be replaced with an else, and you could be rid of the third section altogether.
Your rules in noCharge are more complicated than they have to be. The current function returns true if, and only if, the quantity is at least 100. Since >= covers that, you could reduce the code to one line: return (intQuantity >= 100).
Hungarian notation is dead. Let it rest in peace.
With all that fixed:
function checkQuantity() {
function noCharge(quantity) {
return (quantity >= 100);
}
var quantity = parseInt(prompt("Quantity:", ""));
if (noCharge(quantity)) {
alert("No delivery charge");
} else {
alert("Delivery charge of $5.99");
}
}
Personally i wouldn't even bother with a function for checking whether something is at least 100...but i can see a use for it if the rules ever get more complicated.