views:

121

answers:

3

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);
    }});
+3  A: 

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);
rahul
A: 

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

parseInt

Sarfraz
Don't forget the radix (,10)
James Wiseman
agreed, that's i have posted link for further detail
Sarfraz
+1  A: 

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.

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