-1

I have done everything correct but still, for all values the function is display "Invalid" only. Can someone tell me where is the problem ?

<html>
<head>
<script>
function alpha()
{ 
var x = document.getElementById('input1'); 
var y = x.value;
var z = isNaN(y);
if(z<1 || z>10){console.log("Invalid");} else {console.log("valid");}
}
</script>
</head>

<body> 
<button id="but1" onmouseover="alpha()" style="background:blue;">Click Me</button> 
<p id=para1> Hello! This is paragraph One! </p> 
<input type=text id=input1 > 
</body> 
</html> 

Thanks in advance, and sorry for asking silly question! But, I cant find where code is getting wrong!

1
  • 1
    The returned value of isNaN is not a number but a boolean. Commented Feb 6, 2015 at 22:25

1 Answer 1

2

isNaN returns a boolean and your comparing it to numbers. you'll want to compare x to your range.

if(z || x<1 || x>10)

Here is how I would clean up your code a bit

function alpha(){ 

    //name your variables something meaningful
    var userInputField = document.getElementById('input1');  

    //using parse int tells yourself and future programmers you want an int
    //it also gives you NaN if it's not a number so you don't have to check yourself
    //the 10 is the radix you want to convert to
    var userInputedValue = parseInt(x.value,10); 
    //check explicitly for NaN will save you some headaches
    if(userInputedValue === NaN || userInputedValue<1 || userInputedValue>10){
        console.log("Invalid");
    } else { 
         console.log("valid");
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

You also need parseFloat or parseInt. x is not a number but an element as well.
@zerkms while it is definitely better to use the correct type, wouldn't x be implicitly converted to a number when compared that way?
@t.niese if x is a number isNaN(x) would return false, since x is not not a number
@t.niese no worries. double negatives are always a pain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.