0

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_6035').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.

1
  • This question is similar to: How to convert a string to an integer in JavaScript?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Oct 14, 2024 at 16:45

4 Answers 4

5

Use parseInt function, not (int) casting

Sign up to request clarification or add additional context in comments.

1 Comment

Be sure to use the radix parameter to force base 10 when using parseInt() --- parseInt($("#qty_6035").val(), 10);
3

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>

Comments

3

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);

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.