Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7034369
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T01:10:39+00:00 2026-05-28T01:10:39+00:00

I have a javascript that calculates the percentage from two fields (retail and network)

  • 0

I have a javascript that calculates the percentage from two fields (retail and network) and then dumps that percentage into another field (markup).

As I am relatively new to the world of JS I have ended up reusing the code for several rows of fields. This goes against DRY and KISS principles so I was wondering if you could give me some input on how to optimise my code so that it can handle any two fields and then dump a value to a third field.

Here is a screenshot of my form segment that is using it.

https://i.stack.imgur.com/822wq.png

enter image description here

Here is my code I am using, I have had to reuse it four times and place the code in four functions e.g. (percentage1, percentage2, percentage3, percentage4) each one of these functions deals with a row of fields show in the screenshot.

    function percentage1()
                {


                //the dividee
                x = document.getElementById('tariff_data');
                //the divider
                y = document.getElementById('network_data');

                    //if the first value is lower than the second, append a "-" sign
                    if (x.value < y.value)
                    {
                        z = "-"+(x.value/y.value)*100;
                        document.getElementById('markup_data').value = z;
                    }
                    //not a negative percentage
                    else
                    {
                        z = (x.value/y.value)*100;
                        document.getElementById('markup_data').value = z;


                    }

                }   
function percentage2()
                {


                //the dividee
                x = document.getElementById('tariff_rental');
                //the divider
                y = document.getElementById('network_rental');

                    //if the first value is lower than the second, append a "-" sign
                    if (x.value < y.value)
                    {
                        z = "-"+(x.value/y.value)*100;
                        document.getElementById('markup_rental').value = z;
                    }
                    //not a negative percentage
                    else
                    {
                        z = (x.value/y.value)*100;
                        document.getElementById('markup_data').value = z;


                    }

                }
etc etc.... 

These functions are called using the onchange HTML attribute

Also when I divide by a decimal number it gives the wrong value, any Ideas how to make it calculate the correct percentage of a decimal number?

My code also gives out these strange outputs:

NaN , Infinity

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T01:10:39+00:00Added an answer on May 28, 2026 at 1:10 am

    With regard to DRYing your code out; remember that you can:

    • Pass parameters to your functions and use those arguments within the function
    • Return values using the return keyword

    In your case, you’ve got all your multiplication code repeated. While trying to fix the string vs. number problems maerics has already mentioned, you could do something like this:

    // We're assuming 'dividee' and 'divider' are numbers.
    function calculatePercentage(dividee, divider) {
        var result;
    
        // Regardless of the positive/negative result of the calculation,
        // get the positive result using Math.abs().
        result = Math.abs((dividee.value / divider.value) * 100);
    
        // If the result was going to be negative...
        if (dividee.value < divider.value) {
            // Convert our result to negative.
            result = result * -1;
        }
    
        // Return our result.
        return result;
    }
    

    Then, in your percentage functions, you can just call this code like so:

    function percentage1() {
        var tariff, network, markup;
    
        tariff = parseFloat(document.getElementById('tariff_data').value, 10);
        network = parseFloat(document.getElementById('network_data').value, 10);
        markup = document.getElementById('markup_data');
    
        markup.value = calculatePercentage(tariff, network);
    }
    

    Obviously, you could take this further, and create a function which takes in the IDs, extracts the values from the elements etc., but you should try and build that yourself based on these tips.

    Maerics also makes a very good point which you should take note of; learn more about the Good Parts of JavaScript. Douglas Crockford’s book is excellent, and should be read and understood by all JS developers, IMHO.

    Hope this helps you clean your code up!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Javascript function that calculates a value and re-inserts the value into
I have Javascript that opens another window and registers a click handler for all
I have some javascript that goes out and fetches a javascript class on another
I have a javascript that displays a generated text into a div: document.getElementById('phrase').innerHTML =
I have a form that calculates a total number using Javascript. The code for
I have some javascript that calculates a price and updates a div. However in
I have an html file that accepts user inputs then uses Javascript to calculate
I have JavaScript that is doing activity periodically. When the user is not looking
I have some javascript that I'm trying to retool using jQuery to learn the
I have a javascript that calls a function each 1 minute. That function sends

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.