在IF条件下比较2个javascript数值

时间:2015-03-17 11:05:25

标签: javascript

我在javascript中设置验证函数以验证HTML页面中的值:

<script>
    function validate() {
        var tterr = document.sngo2a.ttime; //This variable captures the value in field ttime              
        var ttserr = document.sngo2a.sngottime; //This variable captures the value in field sngottime

        var errortimecheck = 0;
        if(ttserr.value > tterr.value)
        {
            errortimecheck = 1;
            var sentence31 = "ERROR!!   \n\nTravel time in Stop-&-Go cannot be greater than the \nTotal travel time"; 
            alert(sentence31);
            alert(ttserr.value);
            alert(tterr.value);
        }
        else
        {
            errortimecheck = 0;
        }
    }
</script>

我从html页面获得以下值:

  

ttime = 10
  sngottime = 7

然后我希望不会看到任何警告信息。但是,我收到警告信息“ERROR !!旅行时间.........”

当我将sngottime从7改为1时,让事情变得更加混乱。逻辑运行良好。

当显示tterr.value和ttserr.value的值时,它们似乎正确显示。

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我将在此假设您的ttimesngottime是字符串。

这意味着JavaScript将按照Lexographic顺序(字母顺序)对它们进行评估。

因此,按字母顺序,您的评估将检查以下内容:

  1. 7按字母顺序排在10以后
  2. 确实如此,进入您的第一个代码块并显示alert
  3. 如果将sngottime更改为1:

    1. 1是否按字母顺序出现在10以后?
    2. 没有!转到If语句的else部分
    3. 要解决此问题,请将您的值显式转换为Integers(或任何其他数字类型):

      if(parseInt(ttserr.value) > parseInt(tterr.value))
      {
          errortimecheck = 1;
          var sentence31 = "ERROR!!   \n\nTravel time in Stop-&-Go cannot be greater than the \nTotal travel time"; 
          alert(sentence31);
          alert(ttserr.value);
          alert(tterr.value);
      }
      else
      {
          errortimecheck = 0;
      }