选择选项值比较给出错误的结果

时间:2014-12-19 12:07:03

标签: javascript jquery twitter-bootstrap-3 html-select

之前没有见过这样的东西......当比较两个选择框的选项值时,它有时会给出正确的结果,有时会给出错误的结果。

<select class="form-control" id="p_in_qty" style="width:100px; margin-left:50px;">
<?php
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30);
              foreach ($array as $value) {
                       echo '<option value="'.$value.'">'.$value.'</option>';
                 }
?>
</select>
<select class="form-control" id="p_av_qty" style="width:100px; margin-left:50px;">
<?php
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30);
foreach ($array as $value) {
    echo '<option value="'.$value.'">'.$value.'</option>';
}
?>
</select>
<button type="button"  onClick="check();" class="btn btn-primary btn-md">Check</button> 
function check(){    
         var i_qty = $('#p_in_qty').val();
         var s_qty = $('#p_av_qty').val();    
         if(s_qty > i_qty){           
        alert("s_qty is greater than i_qty") ;    
    }else{
       alert("fine");
      }    
  } 

当我为身份p_in_qty选择“14”而为身份p_av_qty选择“8”时,它会给出错误的结果。对于某些值组合会发生这种情况,而对于某些值则不然。这是我第一次遇到的奇怪的事情。!!这是怎么回事?

2 个答案:

答案 0 :(得分:2)

进行字母比较 要比较数字,你需要解析int

 var i_qty = parseInt($('#p_in_qty').val());
 var s_qty = parseInt($('#p_av_qty').val());

答案 1 :(得分:1)

以为我会留下答案,虽然在我的评论中已经解决了......

您需要将字符串值转换为整数以进行比较... 的 http://jsfiddle.net/v47qdaap/

check = function(){
    var i_qty = parseInt($('#p_in_qty').val(), 10);
    var s_qty = parseInt($('#p_av_qty').val(), 10);

    if(s_qty > i_qty){
        alert("s_qty is greater than i_qty") ;
    } else {
        alert("fine");
    }

}