Artur Lukashchuk
Artur Lukashchuk

Reputation: 5

Realtime changing values with formulas for input type jQuery

I have to inputs:

So if the user type value in the first field: 1000. In the Second field must appear 1010

Code:

$(document).ready(function() {
  $("#summWithoutComission").keyup(function() {
    var thisVal = $("#summWithoutComission").val;
    $("#summWithComission").val(thisVal);
  });
});

Markup:

<input type="text" id="summWithoutComission" name="AMOUNT" maxlength="50" value="1000" class="text-field" />
<input type="text" id="summWithComission" value="" readonly class="text-field" />

Here is fiddle https://jsfiddle.net/9hpyg1pc/4/

Upvotes: 0

Views: 61

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34227

If you want to add a percentage to a number you should multiply that number by 1 plus the percentage fraction.

A percentage fraction is the fraction divided by 100. For your example 1 divided by 100 or 1/100 = 0.01, then add 1 to this percentage fraction so you get 1.01

Using 3490 entry for example 3490+1% = 3490 * 1.01 = 3524.9

Thus for your example it would be:

1000 + 1% = 1000 * 1.01 = 1010

Now to adjust your code: We need to parse it to a numeric value first.

$(document).ready(function() {
  $("#summWithoutComission").keyup(function() {
    var thisVal = parseFloat($(this).val());
    var percentValue = thisVal * 1.01;
    $("#summWithComission").val(percentValue );
  });
});

Now, notice that you have a value already in the first field. SO to get that to calculate you can simply trigger your keyup like so:

$(document).ready(function() {
  $("#summWithoutComission").keyup(function() {
    var thisVal = parseFloat($(this).val());
    var percentValue = thisVal * 1.01;
    $("#summWithComission").val(percentValue );
  }).trigger('keyup');
});

Here is an updated fiddle with that in place: https://jsfiddle.net/MarkSchultheiss/9hpyg1pc/7/

Upvotes: 1

Saleh
Saleh

Reputation: 160

In your fiddle example you need to add jquery as an external js resource:

https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js

But this should resolve your problem:

$(document).ready(function(){
        $("#summWithoutComission").keyup(function(){

             var thisVal=$("#summWithoutComission").val();
             var commVal = (parseFloat(thisVal) * (1/100)) + parseFloat(thisVal);
             $("#summWithComission").val(commVal);

        });
    }); 

Upvotes: 1

Related Questions