JulianJ JulianJ - 6 months ago 7
jQuery Question

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.");
}
}

});

Answer

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);
           var b = parseInt(data.b);


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

   });
Comments