mcabrams
mcabrams

Reputation: 686

Javascript console log clearing itself after if statement evaluates to false

I have the following simple code from an exercise in Modern Javascript used to calculate a sphere's volume, it contains a part which checks to make sure that a value has been entered for radius.

HTML:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Volume of a Sphere Calculator</title>
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    <!-- sphere.html -->
    <form action="" method="post" id="theForm">
        <fieldset>
            <p>Use this form to calculate the volume of a sphere.</p>
            <div>
                <label for="radius">Radius</label>
                <input type="text" name="radius" id="radius" required></div>
            <div>
                <label for="volume">Volume</label>
                <input type="text" name="volume" id="volume"></div>
            <div>
                <input type="submit" value="Calculate" id="submit"></div>
        </fieldset>
    </form>
    <script src="js/sphere.js"></script>
</body>
</html>

JS:

function calculate() {
    'use strict';

    var volume;
    var radius = document.getElementById('radius');

    if (radius && (radius.value > 0)){

        volume = (4/3) * Math.PI * Math.pow(radius.value, 3);

    }
    volume = volume.toFixed(4);

    document.getElementById('volume').value = volume;

    return false;
}

function init() {
    'use strict';
    var theForm = document.getElementById('theForm');
    theForm.onsubmit = calculate;
}

window.onload = init;

Upvotes: 4

Views: 13877

Answers (4)

Quantumk9
Quantumk9

Reputation: 11

You can use el.preventDefault(); in your callback function

Upvotes: 1

User55412
User55412

Reputation: 940

Adding another solution as a Google search for "javascript log disappearing" brought me here.

Page refreshing/navigation was the problem.

Selecting "Preserve log" in the console settings as per mateuszb's comment solved the issue.

Upvotes: 3

Andrew Koper
Andrew Koper

Reputation: 7191

Because this is the top Google match for my problem of console.log output appearing and quickly disappearing, this happened to me because I either had an empty set of label tags out of place or a form with no action. Deleting those tags caused JavaScript and console.log() to work like it was supposed to.

Upvotes: 6

Shmiddty
Shmiddty

Reputation: 13967

Because undefined does not have a method toFixed, which throws an error, preventing Calculate from ever reaching return false;

Since that line is never reached, the form submits, which (generally speaking) posts the form to the same page.

When the page reloads, the console is reset (I believe this depends on the specific browser).

To fix this, initialize volume to 0.

Upvotes: 1

Related Questions