0

我试图让我的输入字段只接受整数并编写了一些 java 来帮助验证,但是每次我单击下一个输入以插入一个值时,它都会发出我的警报。我错过了什么吗?

<script type="text/javascript">
    var cartAmount, subtotal, pstAmount, pstTax, gstTax, taxAmount, shipCharge, afterTax; 

    function validate() {
        //Whole Numbers with Regexp
            var rx = new RegExp(/\d+/);

            if(document.getElementsByClassName("inputValue").value != rx || document.getElementsByClassName("inputValue").value == "") {
                alert("Please use only whole quantities.");
                return false;
            }
    }
    function sumCart() {

        //Adding Cart Values
            cartAmount = (document.frmMain.item1.value * 3.99) + (document.frmMain.item2.value * 5.99); 

        //Finding Subtotals
            document.frmMain.subtotalAmt.value = Math.round(cartAmount*100)/100;
            subtotal = document.frmMain.subtotalAmt.value;

        //Finding Taxes
            pstTax = document.frmMain.taxAmount.value;
            gstTax = .05;

            pstAmount = Math.round((subtotal * pstTax)*100)/100;
            gstAmount = Math.round((subtotal * gstTax)*100)/100;

            taxAmount = parseFloat(pstAmount,10) + parseFloat(gstAmount,10);

            document.getElementById("tax").innerHTML = "Tax in dollars is $" + Math.round(taxAmount * 100)/100;

        //Finding Total
            shipCharge = 0;
            afterTax = parseFloat(subtotal) + parseFloat(taxAmount) + parseFloat(shipCharge);
            document.frmMain.totalAmt.value = Math.round(afterTax*100)/100;
    }
</script>
4

1 回答 1

0

试试这个验证功能:

function validate() {
    //Whole Numbers with Regexp
    var rx = new RegExp(/^\d+$/);
    inputs = document.getElementsByClassName("inputValue");
    for (var i = 0; i < inputs.length; i++) {
        var input = inputs[i].value;
        if (!rx.test(input)) {
           alert("Please use only whole quantities.");
           return false;
        }
    }
}

您的代码有几个问题:

  1. 正则表达式/\d+/只检查值中是否有任何数字,它不检查它是否只有数字。您需要锚定到开头和结尾,^$检查整个值。

  2. 您正在使用value != rx,它不执行正则表达式测试。你必须使用rx.test().

  3. getElementsByClassName返回元素的集合,而不是单个元素。您需要遍历它们以获取值。

于 2013-04-16T00:55:56.493 回答