What is the best way to incorporate multiple calculations in JavaScript?

As a newcomer to JavaScript, I am trying my hand at creating an online tax calculator for our website. While I can understand pre-written calculations, developing my own has proven to be challenging. The objective is simple: the user inputs their Gross Income and clicks "Calculate" to see Tax Payable, Medicare Levy, and Net Income (Gross-Tax-Medicare).

Currently, I have found some foundational code for tax calculations, but I need to tweak it for accuracy. The issue lies in correctly applying the Medicare value as there are actually three different levels based on income brackets.

I'm struggling with merging these calculations and subtracting them from Gross Income to get the Net Result. Before diving into the final calculation, I want to figure out how to integrate multiple functions in one script.

Building this calculator step by step seems like the best approach, yet I hit a roadblock right away. For testing purposes, you can view the progress at .

Any assistance would be greatly appreciated as I await guidance from a JavaScript tutorial to deepen my understanding of the language.

The new Medicare calculation I'm looking to incorporate is outlined below:

// Updated Medicare Calculation:
if (income > 0 && income <= 19404) {
    medicare = (income * 0) / 100;
}
else if (income > 19404 && income <= 22828) {
    medicare = (income * 10) / 100;
}
else if (income > 22828) {
    medicare = (income * 1.5) / 100;
}

Answer №1

To implement the necessary JavaScript code, you can utilize a structure similar to this snippet:

// Ensure jQuery library is included
$(function(){
    // Trigger calculation on button click
    $('#calculate').on('click', function(){
        // Retrieve user-entered income from input field
        var income = parseInt($('#preIncome').val().trim()),
            postIncome = 0,
            medicare = 0;
        console.log(income);
        if(income > 0){
            // Calculate Medicare based on income brackets
            if (income > 0 && income <= 19404) {
                medicare = (income * 0) / 100;
            }
            else if (income > 19404 && income <= 22828) {
                medicare = (income * 10) / 100;
            }
            else if (income > 22828) {
                medicare = (income * 1.5) / 100;
            }
            // Update post-income based on calculated Medicare
            postIncome = income - medicare;
        }
        // Update output fields with new values
        $('#postIncome').val(postIncome);
        $('#medicare').val(medicare);
    });
});​

A live demonstration of this script can be found at: http://jsfiddle.net/pratik136/YdWNA/

Answer №2

To solve the problem at hand, it seems like utilizing two variables is key - one for the medicare calculation and another for the tax rate. By having these values established, you can then compute the net income.

In a JavaScript scenario, the implementation might resemble this approach:

var medicare;
var tax; 
var income;
// Here lies your medicare computation
if (income>0 && income<=19404) {
    medicare = (income*0)/100;
}
else if (income>19404 && income<=22828) {
    medicare = (income*10)/100;
}
else {
    medicare = (income*1.5)/100;
}
// A hypothetical Tax estimation (Actual rates unknown)
if (income>0 && income<=20000) {
    tax = (income*25)/100;
}
else {
    tax = (income*40)/100;
}
// Proceeding to derive the net income with the determined values
var netIncome = income - tax - medicare;

Answer №3

Here is the core of your form:

<form name="calc">

  Gross Income: <input type="text" class="innerc resform" size="15" name="income">

  <input type="button" onclick="calculate(this)" name="result" value="Calculate"
   class="calcButton">

  Income Tax:    <input type="text" size="15" class="resform" name="tax">
  Medicare Levy: <input type="text" size="15" class="resform" name="medicare">
  Net Income:    <input type="text" size="15" class="resform" name="net">
</form>

If you pass this from the calculate button (note the changed listener and addition of a value), a function to calculate the medicare levy can be:

function calculate(element) {
  var form = element.form;
  var income = form.income.value;

  // 0 for income less than threshold
  var medicare = 0;

  // Add 1% of income between 19404 and 22828
  if (income > 19404 && income <= 22828) {
    medicare = (income - 19404) * 0.01;
  }

  // Add 1.5% of income over 22828
  if (income > 22828) {
    medicare += (income - 22828) * 0.015;
  }
}

This should help you get started.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop flash notifications from sliding below the container

Creating a web application using Bootstrap 4, I implemented user notifications with alerts according to the documentation found here. However, I encountered an issue where the content below the alert shifts when the alert is displayed and then shifts back ...

When attempting to call a recursive method in Vue with a changing `this` object, an error is thrown: "RangeError: Maximum call stack size exceeded"

Update integrate codePen into the project. https://codepen.io/jiaxi0331/pen/xxVZBMz Description encountered an issue while trying to call the parent method recursively Code export default { methods: { dispatch(componentName, event, value) { ...

Display a text field upon clicking on a specific link

I am trying to create a text field that appears when a link is clicked, but I haven't been able to get it right yet. Here is what I have attempted: <span id="location_field_index"> <a href="javascript:void(0)" onclick="innerHTML=\"< ...

What is the best way to transform a synchronous function call into an observable?

Is there a conventional method or developer in RxJS 6 library that can transform a function call into an observable, as shown below? const liftFun = fun => { try { return of(fun()) } catch (err) { return throwError(err) } ...

Define a variable using an HTML selector and then verify the presence of elements inside it

One method I use involves creating a variable based on an HTML object. var li = $(this).closest('li'); After creating this variable, I often need to select inner HTML objects from it, such as spans. li.find('span'); However, sometim ...

Checkbox paired with a read-only text column

I have a simple HTML input field with JavaScript functionality, which includes a checkbox. I am trying to write text in the input field when the checkbox is checked, and make the input field read-only when it is not checked. Can anyone provide an example ...

Ensure to update the npm package version before making any Git commit

My project is built with Ember using NPM and I utilize Git for version control. I am looking for a way to update or bump the package.json version before or during a Git commit. Is there a method to accomplish this? Should I be implementing Git hooks? ...

Does the content from an AJAX request get loaded if you flush it using ob_flush()?

Imagine this scenario, where we are making an AJAX request and inserting the result inside a div with the id of "result". On the backend, the script is using ob_flush() to send the header but not terminating the request until it's explicitly terminat ...

Bootstrap along with ROR 3.2.21 has a malfunctioning navbar

I am facing an issue with the Home section in the navbar. It used to work perfectly, but suddenly it stopped displaying as intended. I have checked and confirmed that both boostrap.min.js and boostrap.min.css are loaded properly. I have included boo ...

"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected. Check out my code below: function submitVi ...

Issue with verifying file existence utilizing $.ajax()

I'm currently facing a challenge checking for the existence of a file using $.ajax(). I am cycling through a JSON file with $.each and trying to determine if a specific staff member has an image. If not, I want to default to using the no_photo.jpg ima ...

Fading CSS Background Transition with Responsive Design

One generous member of our online community shared a CSS rollover code that is "fluid" and can adapt to different browser sizes. The code is provided below, along with a link to JsFiddle: CSS .container { width: 100%; height: 300px; backgroun ...

Insert code into the notes section of Pug

Need help inserting a script into a comment on Pug? I have two scripts that need to be added to my website: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="http ...

What is the process for invoking a JavaScript function and storing form data in a text file within an HTML document?

My HTML code is here..... <!DOCTYPE html> <html> <title>Plot</title> <head> <script type="text/javascript" src="d3.min.js"></script> <script> function filter() { var choice = document.ge ...

What methods are available to decrease the width of the clarity stack component label?

Is there a way to decrease the width of the label in the clarity stack component? I attempted to adjust the width using custom styling, but it did not work as expected. Custom styles applied: .myStyle { max-width: 10% !important; flex-basis: 10% ...

Differences between using CSS properties and AngularJS filters:CSS properties

When working on an angularjs application, one task may be to convert a string to uppercase. There are 2 options available to achieve this, both yielding the same result. However, it is important to consider the scenarios in which one option may be preferre ...

Incorporating CSS and JS files into a WordPress theme

To incorporate Css & Js files into my website pages, I plan to insert the following code into the functions.php file: function cssjsloading(){ wp_enqueue_style('bootstrap-rtl', get_template_directory_uri() . '/css/bootstrap-rtl.css&apo ...

Enhance the functionality of your Rails application by implementing Ajax or jQuery to asynchronously load table elements separately from the page

Currently, I am facing an issue with a page that displays a list of user sites. The problem lies in the fact that I am making an API call for each site to check its status, which is causing the page to load very slowly. To address this issue, I would like ...

Animation in CSS3: Blinking overlay block

I am interested in creating an element that will overlay a section of a webpage using position: absolute. The element should be 50% opaque and blink between red and transparent, similar to the way OSX used to do with default dialog buttons. Is there a way ...

Struggling with Implementing Modals in Bootstrap 3.3.7

I've been encountering an issue with modal functionality. In order to troubleshoot my own modals, I decided to replicate the modal example code from Bootstrap's website into a new HTML file. Despite linking to the CDN, the modal does not functio ...