Azib Yaqoob
Azib Yaqoob

Reputation: 37

JavaScript: Alert not working in the script

I am new to JavaScript. This is my second day to start actual learning of JavaScript. I don't know if it is appropriate place to ask this question because there are so many guidelines and standards to follow.

Well, here what I wrote a little script and it is not working. When value < 5 && value > 5 it is showing alerts. But when someone gave the answer 5 (which is the correct answer). It is not showing any alert? I tried myself to resolve this problem but I couldn't resolve this problem. Here is my code:

<script type="text/javascript"> 
    var number = prompt("count these numbers: 2+5-10+8=?");
    if( number === 5 ) {
     alert( "Congratulations Your Answer is Correct" );
    }
    else if ( number > 5  ) {
      alert( "Your answer is a little higher." );
    }
    else if ( number < 5 ) {
      alert( "Your answer is little lower than actual answer." );
    }
</script>

Upvotes: 2

Views: 304

Answers (5)

Ehtasham
Ehtasham

Reputation: 54

Try this one:

ScriptManager.RegisterStartupScript(this, GetType(), "alertmsg", "alert('your message');", true);

Upvotes: -1

Ryan O&#39;Donnell
Ryan O&#39;Donnell

Reputation: 481

When you do a '===' comparison, it checks if the types exactly match up, and in this case youre checking if the NUMBER 5 is equal to the STRING 5 (or whatever else they entered), which is false.

You need to parse the answer into an integer, as David Thomas has already suggested:

var number = parseInt(prompt("count these numbers: 2+5-10+8=?"));

Upvotes: 0

RobG
RobG

Reputation: 147403

The simple answer is to use == instead of strict equality ===.

Don't use parseInt as it will convert say 5iasd to 5, so you'll either accept incorrect answers or need an extra test.

Don't use parseFloat as it isn't required. Using == means that all of the following return true:

var n = 5;

n == '5'
n == '5.0'
n == '5e0'
n == '0.5e1'

and so on.

Oh, for reference, you should learn how the ECMAScript Abstract Equality Comparison Algorithm works.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

I'd suggest:

var number = parseInt(prompt("count these numbers: 2+5-10+8=?"),10);

Upvotes: 3

user1106925
user1106925

Reputation:

The prompt is returning a string, but you're doing a strict equal test for a number.

You can...

  • Test for a string instead with number === "5",

  • or use == instead of ===, which will do a conversion for you,

  • or convert the prompt to a number with number = parseInt(number, 10)

  • or if you'll potentially be testing for floats, use number = parseFloat(number)

Upvotes: 8

Related Questions