Home > Enterprise >  How do I use the compute() event properly for a calculator
How do I use the compute() event properly for a calculator

Time:09-29

I'm trying to code a sample rate calculator and I need the compute() function to display text with certain parameters each time it's pressed, but it's not working

I'll paste the code samples below.

 

var principal = document.getElementById("principal").value;
var rate = document.getElementById("rate").value;
var years = document.getElementById("years").value;
var interest = principal * years * rate /100;
var year = new Date().getFullYear() parseInt(years);


function compute()
{
    var result = document.getElementById("result").value;
    document.getElementById("result").innerHTML = "If you deposit " principal ",\<br\>at an interest rate of " rate "%\<br\>You will receive an amount of " amount ",\<br\>in the year " year "\<br\>";
    
}


function checkdata() {
  //create references to the input elements we wish to validate
  var years = document.getElementById("years");
  var principal = document.getElementById("Principal");

  //Check if "No of Years" field is actual year
  if (years.value != "year") {
    alert("Please input the actual year");
    years.focus();
    return false;
  }
  //Check if principal field is zero or negative
  if (principal.value == "0" || principal.value == "negativ no") {
    alert("Enter a positive number");
    principal.focus();
    return false;
  }
  //If all is well return true.
  alert("Form validation is successful.")
  return true;

}

function updateValue(event) {
 
    document.getElementById("rate_val").innerText = event.value;
  }
    
<!DOCTYPE html>
<html>
    <head>
    <script src="script.js"></script>
    <link rel="stylesheet" href="style.css">
    <title>Simple Interest Calculator</title>
</head>
    <body>
    <div >
        <h1>Simple Interest Calculator</h1>
        
        <form id="form1">
        <label for="Amount"></label>
        Amount <input type="number"  id="principal">  
        <br/>
        <br/>
        <label for="Interest Rate"></label>
        <label for="Interest Rate">Interest Rate</label>
    <input onchange=updateValue(this) type="range" id="rate" min="1" max="20" step="0.25" default value="10.25">
    <span id="rate_val">10.25%</span>
        <br/>
        <br/>
        <label for="No. of Years"></label>
        No. of Years <select id="years">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
            <!-- fill in the rest of the values-->
        </select> 
        <br/>
        <br/>
        
        <label for="Compute Interest"></label>
        <button onclick="compute()">Compute Interest</button>
        <br/>
        <br/>
        <span id="result"></span>
        <br/>
        <br/>

        </form>
        <br/>
        <br/>
       
        <footer>&#169; Everyone Can get Rich.<br/>This Calculator belongs to Igho Emorhokpor</footer>
        </div>

    </body>
    </html>

CodePudding user response:

The main issue in your code is because you've attached the onclick attribute to the button which submits the form. As the form submission is not being prevented, the page is redirected before you can update the DOM.

To fix this, hook the event handler to the submit event of the form and call preventDefault() on the event which is passed to the handler as an argument.

In addition, there's some other issues in your code.

  • You should avoid using onX attributes as they are no longer good practice. Attach your event handlers using unobtrusive JS, such as addEventListener().
  • amount is not defined anywhere. You will need to declare and set this variable. I've used a dummy value for it in the code below.
  • You need to retrieve the value properties of your form controls when the button is clicked, not when the page loads. This is to ensure that the values the user enters are retrieved from the DOM.
  • Wrap the field controls and the label text within the label element. Leaving them empty serves no purpose.
  • Avoid using the <br /> tag as much as possible. Given the above change to your label elements, apply CSS to add the margin underneath them instead.
  • In the checkData() function, years is a selection of integer values, so comparing those values to a "year" string is redundant.
  • In addition, to detect a negative number compare it to < 0, not the string "negative no"

With all that said, try this:

let principalEl = document.querySelector("#principal");
let rateEl = document.querySelector("#rate");
let rateOutputEl = document.querySelector('#rate_val');
let yearsEl = document.querySelector("#years");
let formEl = document.querySelector('#form1');
let result = document.querySelector('#result');
let amount = '???';

formEl.addEventListener('submit', e => {
  e.preventDefault();
  
  if (!checkData())
    return;

  let principal = principalEl.value;
  let rate = rateEl.value;
  let year = yearsEl.value;

  let interest = principal.value * years.value * rate.value / 100;
  let endYear = new Date().getFullYear()   parseInt(years.value);

  result.innerHTML = `If you deposit ${principal},<br \>at an interest rate of ${rate}%<br \>You will receive an amount of ${amount},<br \>in the year ${endYear}<br \>`;
});

rateEl.addEventListener('input', e => {
  rateOutputEl.textContent = e.target.value   '%';
});

function checkData() {
  let principal = principalEl.value;
  if (!principal || parseFloat(principal) < 0) {
    alert("Enter a positive number");
    principalEl.focus();
    return false;
  }
  
  return true;
}
label {
  display: block;
  margin-bottom: 20px;
}

form {
  margin-bottom: 50px;
}
<div >
  <h1>Simple Interest Calculator</h1>

  <form id="form1">

    <label for="Amount">
      Amount
      <input type="number" id="principal">
    </label>

    <label for="Interest Rate">Interest Rate
      <input type="range" id="rate" min="1" max="20" step="0.25" value="10.25" /> 
      <span id="rate_val">10.25%</span>
    </label>

    <label for="No. of Years"> 
      No. of Years
      <select id="years">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <!-- fill in the rest of the values-->
      </select>
    </label>

    <label for="Compute Interest">
    <button type="submit">Compute Interest</button>
    </label>
    
    <span id="result"></span>
  </form>
  <footer>&#169; Everyone Can get Rich.<br/>This Calculator belongs to Igho Emorhokpor</footer>
</div>

CodePudding user response:

function compute()
{
    var result = document.getElementById("result").value;
    document.getElementById("result").innerHTML = ~If you deposit ${principal} at an ${interest} rate of ${rate}% You will receive an amount of ${amount} in the year ${year}~;
    
}

CodePudding user response:

function compute() {
  var result    = document.getElementById("result").value;
  var principal = 100
  var rate      = 2
  var amount    = 3
  var year      = 2022
  document.getElementById("result").innerHTML = "If you deposit "   principal   ",\<br\>at an interest rate of "   rate   "%\<br\>You will receive an amount of "   amount   ",\<br\>in the year "   year   "\<br\>"
}
<label for="Compute Interest"></label>
<button onclick="compute()">Compute Interest</button>
<div id="result"></div>

  • Related