开发者

Syntax error. Help with one small JS snippet :(

开发者 https://www.devze.com 2023-01-02 16:07 出处:网络
Hey guys. I don\'t know much JS, but I wanted to do some quick work with jQuery. But I\'ve been staring at this for about an hour and I don\'t understand what I missed:

Hey guys. I don't know much JS, but I wanted to do some quick work with jQuery.

But I've been staring at this for about an hour and I don't understand what I missed:

<script type="text/javascript">
    $('#qty_6开发者_Python百科035').change(function () {
        var substractedQty, stockQty, remQty;
        substractedQty = (int) $('#qty_6035').val(); // missing ; before statement 
        stockQty = (int) $('#orig_qty_6035').val();
        $('#rem_qty_6035').html(stockQty-substractedQty);
    });
</script>

jQuery library is included at the beggining of the document.

Thanks.


Use parseInt function, not (int) casting


Javascript is a dynamic language so in order to convert a string into a number you could use the parseFloat/parseInt functions:

<script type="text/javascript">
    $('#qty_6035').change(function () {
        var substractedQty = parseFloat($('#qty_6035').val());
        var stockQty = parseFloat($('#orig_qty_6035').val());
        $('#rem_qty_6035').html(stockQty - substractedQty);
    });
</script>


JavaScript is not Java. int is a reserved keyword but doesn't have any functionality assigned to it, and you can't cast a value that way.

You probably want:

substractedQty = parseInt($('#qty_6035').val(), 10);


Javascript doesn't support type casting like strong typed languages (C#, Java) do. To convert the field values (which are strings) to numbers you need to use the global functions parseInt() or parseFloat().

You'll probably also want to make sure the values are parsed correctly, in case a user entered some bad input instead of a number. Use isNAN() for that.

0

精彩评论

暂无评论...
验证码 换一张
取 消