Jump to main content

Calculator

You'll find calculators on many websites; ranging in complexity from very simple to extremely complicated. Javascript is one of the most common tools for coding calculators. Sometimes the figures used in calculations need to change. WebYep can help build a calculator that an author is able to login and edit (with zero code). This example extends the 'data' snippet, in allowing a website author to login and set the interest rate of a bank account. When the customer types their investment amount into the calculator, our WebYep-editable interest rate is applied, with the answer shown to the customer.

Example

 

HTML & PHP

<?php if(webyep_bIsEditMode() == false) : ?>
<form action="#" id="calculator"
data-interest-rate="<?php endif; ?><?php webyep_shortText("Interest Rate", false, 550, 240); // WebYepV2 ?><?php if(webyep_bIsEditMode() == false) : ?>">
  <label for="amount">Amount to invest:</label>
  <input type="number" id="amount" min="0">
  <button type="submit" class="btn">Calculate</button>
  <p id="answer"> </p>
</form>
<?php endif; ?>

CSS

#calculator {
    display: flex;
    flex-wrap: wrap;
}

#calculator label {
    width: 100%;
    font-weight: bold;
}

#calculator input[type="number"],
#calculator .btn {
    margin: 0.5rem 0;
    border-radius: 0.25rem;
    font-size: 15px;
}

#calculator input[type="number"] {
    flex: 1;
    border: 1px solid #666666;
    padding: 0.5rem;
    margin-right: 0.5rem;
}

#calculator .btn {
    padding: 0.5rem 1rem;
    margin: 0.5rem 0;
    border: 1px solid rgba(59, 130, 246, 1);
    background-color: rgba(59, 130, 246, 1);
    color: #fff;
}

.btn:hover {
    background-color: rgba(59, 130, 246, 0.9);
    border-color: rgba(59, 130, 246, 0.9);
}

.btn:active {
    transform: scale(0.97);
    background-color: rgba(59, 130, 246, 0.9);
    border-color: rgba(59, 130, 246, 0.9);
}

#calculator #answer {
    width: 100%;
}

Javascript

const calculator = document.querySelector('#calculator');
const answer = calculator.querySelector('#answer');

calculator.addEventListener('submit', (event) => {
    event.preventDefault();
    const amount = parseFloat(calculator.querySelector('#amount').value);
    const interestRate = parseFloat(calculator.dataset.interestRate);
    const decimalPercent = (interestRate / 100);
    const accruedInterest = (decimalPercent * amount);
    const totalInvestment = (amount + accruedInterest);
    if (!isNaN(amount)) {
        answer.innerHTML = `
        With an interest rate of ${interestRate}%, if you invest $${amount}, you'll earn $${accruedInterest.toFixed(2)}, giving you a total of $${totalInvestment.toFixed(2)}.
        `;
    } else {
        answer.innerHTML = `
        Please enter an investment amount, in the box above.
        `;
    }
});