You are viewing limited content. For full access, please sign in.

Question

Question

Percent change formula in Javascript

asked on February 9, 2015 Show version history

In LF Forms we have a field that needs to calculate the % change between two salaries (current and new).  We have tried the below javascript/css combo but it's not working.  

CSS:

Current Sal: num1

New Sal: num2

%change: numtotal

 

JavaScript:

$(document).ready(function () {
$('.num1').on('blur change', '.num1 input', numtotal);
$('.num2').on('blur change', '.num2 input', numtotal);

function numtotal() {
var num1 = num1.value;
var num2 = num2.value;
return ((num2 - num1) / num1 * 100 + "%");
}

0 0

Answer

APPROVED ANSWER
replied on February 9, 2015 Show version history

you are definitely not referring to the fields accurately. You also did not include the close parenthesis on the end of your javascript. I have gotten the following code to work. I even made it round to have two decimals only.

BTW, make sure you are using a field that accepts numbers and percentage signs, such as the Single Line type field. 

 

$(document).ready(function () {
  function round(val){
   return Math.round(val * 100) / 100;
  }

  function numtot() {
    var num1 = $('.num1 input').val();
    var num2 = $('.num2 input').val();

    var result = num2 - num1;
    result = result / num1;
    result = round(result);

    $('.numtotal input').val( result+'%');
  }

  $('.num1').on('change blur', 'input', numtot);
  $('.num2').on('change blur', 'input', numtot);
})

 

0 0
replied on February 9, 2015

This worked great!  Thank you!

0 0

Replies

replied on August 23, 2019

I am calculating percentages for each row in a table as shown below. If I change one row, all the rows are changing. How do I make it work just for the current row?

 

0 0
replied on August 26, 2019

Any update please?

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.