JulianJ
JulianJ

Reputation: 1317

Why does my if else condition not work in jquery?

I am trying to add a condition to some jquery script but for some reason I can't get it to work. I hope someone can tell me what I have got wrong. I want the script to show different text in a div depending on the value of a variable gotten through ajax. Many thanks.

The ajax bit of my script

$(document).ready(function() {

       //Fetch data from server

       $.ajax({
           url: 'my_data.php',
           dataType: "json",
           success: function(data) {

               $("#a").text(data.a);
               $("#b").text(data.b);

               var a = data.a;
               var b = data.b;


               //Condition
               if (a > b) {
                   $("#advice").text("a is greater than b");
               } else {
                   $("#advice").text("b is greater a.");
               }
           }

       });

Upvotes: 0

Views: 50

Answers (2)

Elwin Arens
Elwin Arens

Reputation: 1602

Depending on the data types of data.a and data.b you might get unexpected behaviour if they're not of the type number.

If data.a and data.b are strings, arrays or Object types, using relational operators will result in behaviour that might not be expected, for example:

console.log('19' > '109'); // false
console.log([1,2] > [2,3,4]); // false
console.log({} > {1: 2}); // false

You can convert strings to float using parseFloat(data.a) or int using parseInt(data.a, 10). The 10 is the radix.

To see what the types are of data.a and data.b are use the typeof keyword:

console.log(typeof data.a);
console.log(typeof data.b);

If these aren't Number, then convert them to float or int before using relational operators.

Upvotes: 1

martiendt
martiendt

Reputation: 2216

try parsing your variable to integer using parseInt(a)

$(document).ready(function() {

   //Fetch data from server

   $.ajax({
       url: 'my_data.php',
       dataType: "json",
       success: function(data) {

           $("#a").text(data.a);
           $("#b").text(data.b);

           var a = parseInt(data.a, 10);
           var b = parseInt(data.b, 10);


           //Condition
           if (a > b) {
               $("#advice").text("a is greater than b");
           } else {
               $("#advice").text("b is greater a.");
           }
       }

   });

Upvotes: 3

Related Questions