“This is the 27th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

Realize individual income tax function

Blue bridge first online simulation game of the third question, let us achieve a personal income tax calculation function, native implementation

The specific requirements

The specific requirement of the question is that different salaries are calculated according to the percentage of different scales, that is, when the salary is less than 5K, the tax part is not included, and the proportion that exceeds the salary is multiplied by the corresponding proportion of different amounts. Here is the HTML structure, a form, a button and a piece of text. We enter our salary in the form and calculate the final result through events.

<input type="number" required class="form-control" style="width: 50%;" <button type="submit" class=" BTN bTN-primary "id=" btn-submit "> <p> You need to pay tax <span id="val">0</span> yuan </p>Copy the code

Function implementation

  1. DOM binding

    First, we need to bind the three DOM elements to the required events, that is, we need to bind a click event to the button, and get the salary data we fill in the form through the DOM, and then make a judgment as a hint. Finally, because of the string we get, So we need to convert our salary string to a number by using parseInt, which we then calculate through the salary calculation function, and finally bind to the paragraph we set and render

    document.getElementById("btnsubmit").onclick = function() { var salary = document.getElementById("salary").value; // if (salary <= 0) {alert(" salary cannot be 0 or less than 0"); return false; } var result = cal(parseInt(salary)); document.getElementById("val").innerText = result; };Copy the code
  2. Salary calculation function

    Is the most important is the salary calculation function, first take a look at my original writing a solution, we are using the if nested, which you need to determine the amount of each range, and then to calculate the final data, so that the code is very troublesome, and still in the game is very time-consuming, which I also for some grammar, and logic is not skilled, So I’m going to write it the other way.

    var shui; if (salary <= 5000) { shui = 0; } else if (salary <= 9000) {shui = (salary - 5000) * 0.03; } else if (salary <= 1000) {shui = (salary - 5000) * 0.05; } else {shui = (salary - 5000) * 0.1; } return shui;Copy the code

    Is this written by? : to calculate, the code is simple, so when we have to use multiple judgments to calculate the scene, we can use this code, effectively reduce code redundancy

    let res = salary <= 5000 ? 0 : salary <= 9000 ? (salary -1000) * 0.03: salary <= 1000? (salary-5000) * 0.05: (salary-5000) * 0.1 return resCopy the code