0

I have below code which is not working.

var day = $("#day").val();
var week = $("#week").val();
var month = $("#month").val();

if (day > week) {
    alert(day > week);
    $('#error').text("Day Limit Must be smaller than Week Limit");
    $('.alert-danger').show();
    setTimeout(function () {
        $(".alert-danger").hide();
    }, 5000);
    return false;
}
if (day > month) {
    $('#error').text("Day Limit Must be smaller than Month Limit");
    $('.alert-danger').show();
    setTimeout(function () {
        $(".alert-danger").hide();
    }, 5000);
    return false;
}
if (month < week) {
    $('#error').text("Week Limit Must be smaller than Month Limit and greater than Day Limit");
    $('.alert-danger').show();
    setTimeout(function () {
        $(".alert-danger").hide();
    }, 5000);
    return false;
}

Here i am getting day=4 and week=6 and month=9. In this case all if conditions are working fine. But month=10, second if condition not working (4>10) is actually false but it getting true.

What's wrong in my logic?

Durga
  • 545
  • 7
  • 21
  • 39
  • 2
    `.val()` returns string, you need to convert it to Number – Satpal Apr 18 '17 at 11:02
  • 2
    You're comparing **strings**. There's a duplicate around here somewhere... (`val` returns a string in the normal case [abnormal cases: an empty jQuery object or a non-field element in the jQuery object, in which case you get `undefined`].) – T.J. Crowder Apr 18 '17 at 11:03

2 Answers2

1

You should convert the values into integers before comparing

var day = parseInt($("#day").val());
var week = parseInt($("#week").val());
var month = parseInt($("#month").val());
Dan Philip Bejoy
  • 4,321
  • 1
  • 18
  • 33
0

You need to cast those values to integers via parseint first to compare them as numbers.

Martin Adámek
  • 16,771
  • 5
  • 45
  • 64