0

Fair warning i'm a JS beginner:

Trying to make a beginner project (tip calculator). I've been stuck trying to make this work for too long.

I'm trying to take the values of the inputs / selects, do an equation, & display the result at the bottom.

But the function is showing immediately and not when the button is clicked... and it's showing NaN instead of the value i intend it to. What am I Missing?

const billInput = document.getElementById('billInput');
const serviceInput = document.getElementById('serviceInput');
const peopleInput = document.getElementById('peopleInput');
    
const tipBtn = document.getElementById('tipBtn');
    
const tipOutput = document.getElementById('tipOutput');
    
tipBtn.addEventListener('click', tipCalculation());
    
function tipCalculation() {
    let cost = Number(billInput.value);
    let service = Number(serviceInput.value);
    let people = Number(peopleInput.value);
    
    document.getElementById('tipOutput').innerHTML = cost * service / people;
}
<div class="main-box">
    <h2 class="title-top">What Should I Tip?</h2>
    <div class="input-group">
        <div class="pre">$</div>
        <input type="number" id="billInput" placeholder="How much was the bill?">
    </div>

    <p class="titles service-title"></p>
    <select required name="Service-lvl" id="serviceInput">
        <option disabled selected>How was the service?</option>
        <option value=".35">Amazing!</option>
        <option value=".25">Solid</option>
        <option value=".15">Meh...</option>
    </select>

    <div class="input-group bottom-input">
        <input type="number" id="peopleInput" placeholder="How many are you splitting with?">
    </div>
    
    <button class="tipBtn" id="tipBtn">How Much Are You Tipping?</button>
    
    <h3 id="tipOutput">Tip Ammount</h3>
</div>
David
  • 208,112
  • 36
  • 198
  • 279
  • 3
    In the `.addEventListener()` call, it should be `tipCalculation` not `tipCalculation()` – Pointy Sep 27 '20 at 15:33
  • 1
    (Just as side note: Counterintuitively, `NaN` is a number. :-) For instance, `Number("x")` results in `NaN` which is of type `number`. There's a reason for it, but that doesn't mean it doesn't seem really weird at first.) – T.J. Crowder Sep 27 '20 at 15:36

0 Answers0