Search code examples
javascripthtmlinnerhtml

InnerHTML problems with Tip Calculator function


I'm trying to write a simple Tip Calculator for a computer science class I'm in. It's in HTML/JavaScript. The actual Tip Calculating function is written in JavaScript. I've been told to use innerHTML to display the output of the function in HTML. So from my understanding, innerHTML works by writing any value/variable (in this case the output of my function) to an HTML container with whatever id is defined.

At first I thought maybe it was just my code being in the wrong order. But I've tried moving the function definition around and that wasn't any help. I've verified that the input ID is correct when pulling the variables from HTML. I've done a lot of reading on similar problems and I can't seem to find what I'm doing wrong.

So heres where I define my function, and use innerHTML to write the output. The function is defined before the actual user input.

function calculateTip(){
        var checkAmount = document.getElementById("amountBox").value;
        var percentTip = document.getElementById("tipBox").value;
        var tipTotal = checkAmount * (percentTip / 100);
        document.getElementById("tipVar").innerHTML = tipTotal;
}
<body>
    <P>
      Enter the check amount: 
          $<input type="numeric" id="amountBox" size=10 value="">
      <br>
      Tip percentage: 
          %<input type="numeric" id="tipBox" size=4 value="">

    </P>
    <input type="button" value="Calculate Tip"
    onclick="calculateTip();" >
                  
    <hr>
    <div id="tipVar"></div>

  </body>

So, I'm expecting when you enter the check amount and tip percentage and click the "Calculate Tip" button, it will run the function and innerHTML will write the output of the function to the page in the div container. However when I click the button seemingly nothing happens. If anyone has any help/guidance I'd greatly appreciate it.


Solution

  • You need to put "tipVar" in quotations inside your function. Otherwise the value of an undefined variable called tipVar is passed in instead, and it finds no element by that id.