2

I have search everywhere on SOF but none of solution worked for me, I need help with calculating float values from a form to javascript on keypress.

I have two fields in form & I want to calculate the values.

<input name="Package[sms]" id="Package_sms" type="text">
<input name="Package[sms_rate]" id="Package_sms_rate" type="text">

Here is my javascript code.

$('#Package_sms, #Package_sms_rate').keypress(function () {
     var sms = parseFloat($("#Package_sms").val());
     var rate = parseFloat($("#Package_sms_rate").val());
     console.log(rate);
     // other code
     console.log(sms*rate);
});

I'm trying to get the value of Package_sms_rate, When I input the value 0.1, the console shows 0.1 perfectly but when I input any of these values 0.11 or 0.12 to 0.19, it still shows 0.1. It is making wrong calculations because of that. How do i fix it?

sms = 50000
rate = 0.1
total = 5000

sms = 50000
rate = 0.1 // when i enter 0.12
total = 5000 // still showing 5000, it should be 6000 for rate 0.12
Asfandyar Khan
  • 1,677
  • 15
  • 34

1 Answers1

1

You need to change your keypress event to a keyup event, so that it triggers after the value has been applied to the input:

Note: I replaced your parseFloat() by the + operator, it's shorter and much more versatile.

$('#Package_sms, #Package_sms_rate').keyup(function () {
     var sms = +$("#Package_sms").val();
     var rate = +$("#Package_sms_rate").val();
     console.log(rate);
     console.log(sms*rate);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="Package[sms]" id="Package_sms" type="text">
<input name="Package[sms_rate]" id="Package_sms_rate" type="text">
Zenoo
  • 12,670
  • 4
  • 45
  • 69