2

Trying to multiply 2 values. Quantity is integer and credit price is decimal number. When I run this code nothing happens.

Does anyone know what is the issue?

Thank you.

 $(function(){ // bind the recalc function to the quantity fields

    $("#oneCreditSum").after('<label></label>Total: Aud <span id=\"total\"></span><br><br>');

    $("#quantity").bind('keyup', recalc);

    function recalc(){
        var quantity = $('#quantity').val();
        var creditPrice = $('#creditPrice').val();
        var total = quantity * creditPrice;
        $("#total").text(total);
    }});
2
  • Is there any javascript error you're getting? Commented Dec 23, 2009 at 10:49
  • Can you add the html? #quantity - a textbox? so is #creditPrice? Commented Dec 23, 2009 at 11:19

3 Answers 3

5

Use parseFloat on the values, and alert each one individually to test.

A few other (unrelated) improvements:

  1. Use keyup() function:

    $("#quantity").keyup(recalc);
    
  2. Make function anonymous:

    $("#quantity").keyup(function(){...});
    
  3. Use $(this) on #quantity in the function to avoid calling the jQuery selector again

You could also consider condensing this into a single line of code:

    $("#total").text(parseFloat($('#quantity').val()) * parseFloat($('#creditPrice').val()));

To zero-pad you might try something toFixed():

var num = 10;
var result = num.toFixed(2); // result will equal 10.00

I got this snippet from the following site

http://www.mredkj.com/javascript/numberFormat.html

Hope this helps.

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

2 Comments

thank you, that was very helpful. one more subquestion: is there a way of limiting the decimal point to show e.g. 10.20 ?
Edited my answer with this. Would you consider accepting this as your answer
5

use

parseFloat

before calculation on both numbers which parses a string argument and returns a floating point number.

var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = parseFloat(quantity) * parseFloat(creditPrice);

Comments

0

If you are interested in whole number only you can use this function instead:

parseInt

1 Comment

agreed, that's i have posted link for further detail

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.