0

I need to create code which automatticaly calculates the circumference when the length and width are entered in two different boxes.

I managed to do so, but I want the answer to appear underneath the "calculate" button, but the answer will make the button and boxes disappear. Could someone tell me what I need to change?

Here is my code:

<!DOCTYPE html>
  <html>
    <body>
      <form>
         Width:<br>
           <input id="Width" type="text" name="Width">
         <br>Length<br>
           <input id="Length" type="text" name="Length">
         <br><br>
           <input type="button" value="Calculate circumference" onclick="doMath()">
     </form>

     <script>
       function doMath() {
          var Width1 = document.getElementById('Width').value;
          var Length1 = document.getElementById('Length').value;
          var Circ = parseInt(Width1) + parseInt(Width1) + parseInt(Length1) + parseInt(Length1);
          document.write(Circ);
       }
     </script>
   </body>
</html>


        
Prime
  • 2,544
  • 1
  • 3
  • 19

2 Answers2

0

Do not use document.write function. The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML. Create a paragraph tag and give an id and place your result in that paragraph.

 <!DOCTYPE html>
    <html>

    <body>
      <form>
         Width:<br>
           <input id="Width" type="text" name="Width">
         <br>Length<br>
           <input id="Length" type="text" name="Length">
         <br><br>
           <input type="button" value="Calculate circumference" onclick="doMath()">
           <p id="result">
           
           </p>
     </form>

     <script>
       function doMath() {
        var Width1 = document.getElementById('Width').value;
        var Length1 = document.getElementById('Length').value;
        var Circ = parseInt(Width1) + parseInt(Width1) + parseInt(Length1) + parseInt(Length1);
        //document.write(Circ);
        document.getElementById("result").textContent = Circ;
     }
     </script>

     </body>

     </html>
mr hr
  • 2,925
  • 2
  • 5
  • 17
0

Try adding a black paragraph to the html and then use document.getElementById("").innerHTML to change the text inside of it.