Jack Billy
Jack Billy

Reputation: 7211

How to do maths in if and else in jquery?

Hello guys!

I have been trying to create a if/else statement code in jQuery but I guess my if/else statement is resting in peace! I don't know what is getting wrong I have did everything and still it is not working correctly! Ok, here is my problem list ~

  1. My if/else is getting inverse!
  2. And I think everything is just getting messed up!
  3. JsLint (in jsFiddle.net) is showing no error in my jQuery code!

Please here is my problem demo link ~~~~~~~~~~

PROBLEM DEMO

Here is my smaple jQuery code ~~~~~~~~~

$(function () {

  var correct = '10';
  var incorrect = '9';

  $('div.correct_incorrect').css("background",function () {

      if( correct > incorrect )
      {
         return "#796";
      }
      else if( correct == incorrect )
      {
         return "#345";
      }
      else
      {
         return "#732";
      }

  });
});

Please help me out!

THANKS IN ADVANCE

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sorry to bother guys but my previous question is solved but I'm having a new problem with this code. Here I'm trying to retrive a value from two input elements! But it is not working.

Please have a look here ----

PROBLEM DEMO 2

THANKS IN ADVANCE (for this one too!)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Upvotes: 2

Views: 256

Answers (5)

iRaivis
iRaivis

Reputation: 169

You are comparing strings. It should be like this (without quotes):

var correct = 10;
var incorrect = 9;

Upvotes: 2

You're comparing string literals '10' and '9' instead of integer values 10 and 9. '9' is bigger than '10' when comparing strings.

Upvotes: 1

Tom Maeckelberghe
Tom Maeckelberghe

Reputation: 1999

Fixed use integers instead of strings:

http://jsfiddle.net/aj49m/2/

Upvotes: 1

Gary Chambers
Gary Chambers

Reputation: 25858

You need to remove the single-quotes from around your correct and incorrect variables. Currently, they are being treated as strings, not integers.

var correct = 10;
var incorrect = 9;

http://jsfiddle.net/aj49m/1/

Upvotes: 2

Justin Ethier
Justin Ethier

Reputation: 134207

The problem is that correct and incorrect are strings. You can change them to integers to fix your problem:

                  var correct = 10;
                  var incorrect = 9;

Alternatively, you can use parseInt(myNumAsString, 10) to convert a string to a number at runtime.

Upvotes: 7

Related Questions