Javascript数值变量比较不起作用

时间:2015-01-15 16:34:46

标签: javascript

我有一个带有2个提交按钮的表单。一个用于Approve,另一个用于Reject

HTML is

<form action="test.php" method="post" name="sos_submit" id="sos_submit">

  <input type="text" name="qty_indented" value="<?php echo $qty_indented ?>" id="qty_indented" readonly="readonly" />
  <input type="text" name="qty_approved" value="<?php echo $qty_approved ?>" id="qty_approved" />
  <input type="submit" name="da_approve" value="APPROVE" onclick="return submitForm(this)" />
  <input type="submit" name="da_reject" value="REJECT" onclick="return submitForm(this)" />

</form>

我的submitForm(this)功能如下:

<script>
function submitForm (button){

    if (button.value == "APPROVE"){
        var qty_approved = document.getElementById("qty_approved").value;
        var qty_intended = document.getElementById("qty_indented").value;
        if (qty_approved <= 0){
            alert("Please Enter the Quantity for Approval!");
            submitOK = "false"; 
        }
        else if(qty_approved >= qty_intended){
            alert("Quantity Approved " + qty_approved + " Cannot be more than quantity intended " + qty_intended + " !");
            submitOK = "false";
        }
        if (submitOK == "false") {
            return false;
        }
    }
    else{
        confirm("Are you sure you want to REJECT the Voucher?");    
    }
}
</script>

虽然它的代码非常简单,但不知何故不能正常工作。

即使qty_approvedLESS而不是qty_indentedif()语句也在执行。

例如,如果qty_approved = 5qty_indented = 10,则代码应提交表单,但不是。它显示:Quantity Approved 5 Cannot be more than quantity intended 10 !

我做错了吗?

1 个答案:

答案 0 :(得分:4)

输入框是基于字符串的值。您需要使用parseInt将值转换为整数:

var qty_approved = parseInt(document.getElementById("qty_approved").value, 10);
var qty_intended = parseInt(document.getElementById("qty_indented").value, 10);

目前它正在比较'5'到'10',按字母顺序'5'大于'10',这就是为什么它会进入这种状态。