简体   繁体   English

Javascript计算器-逗号问题

[英]Javascript Calculator - issues with commas

I am very new to Javascript; 我是Java的新手。 as in about 3 days new... I am working on creating a calculator to extract data from three input fields and then calculates out to a rough monthly and yearly total. 就像大约三天后一样...我正在创建一个计算器,用于从三个输入字段中提取数据,然后计算出大致的每月和每年总计。 It then uses this total to dynamically build out a table. 然后,它使用此总数来动态构建表。

For the most part I have everything working, with one exception. 在大多数情况下,我可以进行所有工作,只有一个例外。 If someone types a comma into the input fields it will only recognize the value before the comma. 如果有人在输入字段中输入逗号,它将仅在逗号之前识别该值。 So for example if they type 10,000; 例如,如果他们输入10,000, it will read it as 10. I've tried to place in a Regex based replace, but it doesn't seem to be working. 它将读为10。我尝试放置在基于Regex的替换中,但似乎不起作用。 I may be placing it in the wrong place, but I tried it a few different ways, so now sure. 我可能将其放置在错误的位置,但是我尝试了几种不同的方法,所以现在确定。

Below is the portion of the code that I am having trouble with. 以下是我遇到问题的部分代码。

    <input onblur="findTotal();" type="text" name="qty" id="qty1"/>
    <input onblur="findTotal();" type="text" name="qty" id="qty2"/>
    <input onblur="findTotal()" type="text" name="qty" id="qty3"/>

    <input disabled type="text" name="totalyr" id="totalyr"/>
    <input disabled type="text" name="totalmo" id="totalmo"/>

    <script type="text/javascript">
    function findTotal(){
        var getqty = document.getElementsByName('qty');
        var tot=0;
        for(var i=0;i<getqty.length;i++){
            if(parseInt(getqty[i].value))
                (tot += parseInt(getqty[i].value));
        }
        document.getElementById('totalmo').value = tot*4;
        document.getElementById('totalyr').value = tot*52;
    }
    </script>

I've tried making the inputs numbers as well, but that did nothing. 我也尝试过使输入数字,但这没做。

Any advice would be greatly appreciated! 任何建议将不胜感激!

Had this yesterday, this is what worked for me 昨天有这个,这对我有用

    var getqty = document.getElementsByName('qty').value.replace(/,/g, "");

alternatively something like 或者像

    var getqty = +document.getElementByName("qty").value.replace(/[^\de.-]/gi, "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM