Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript to modify HTML content

Doubtful this needs much explaining but I think I need a second set of eyes to check this out because I just cannot fathom why it won't! Try using the "Energy Calculator" and no value will be returned when submitted despite me approaching it in the same way as the "Battery Charge Calculator" which does work.

Link: http://jsfiddle.net/Deva/426Jj/

like image 353
Matt Avatar asked Dec 05 '22 22:12

Matt


2 Answers

To elaborate on @alex's answer, you have selected the onLoad option of jsFiddle, which places your JavaScript code inside of an anonymous function:

window.onload = function() {
    function energyCalc() {
        var mass = document.forms['0'].mass.value;
        var finalMass = mass * 1000;
        var velocity = document.forms['0'].velocity.value;
        var finalVelocity = velocity * 0.3048;
        var energy = (0.5 * (finalMass * (finalVelocity * finalVelocity)));
        if ((mass && velocity) != '') {
            document.getElementById("energy").innerHTML = 'Energy of weapon: ' + energy + ' Joules';
        } else {
            document.getElementById("energy").innerHTML = 'You must enter values in both fields!';
        }
    }
}

Try this on for size: http://jsfiddle.net/mattball/Cbsa8/. All I did was select no wrap (head) and No library.

Keep in mind that it's better coding practice to write unobtrusive JavaScript. In this case you'd bind the event handler with JavaScript, using attachEvent (for IE <9) or addEventListener (for real browsers).


Edit re: OP edits

Open a console and the problem is immediately obvious after trying to use the Energy Calculator:

> Uncaught TypeError: Cannot read property 'value' of undefined (fiddle.jshell.net:100)

which is this line:

var mass = document.forms['0'].mass.value;

You're accessing the wrong form. You need to change all cases of forms['0'] to forms[1] in the energy calculator's code. Note the omitted quotes, by the way - document.forms is an array, not an object!

Also, you're clearly using jQuery, but you're not using it everywhere you could. Why not? There's a lot of room for improvement in your code. It's cleanup time!

HTML

<div id="main">
    <a href="#"><h3>Battery Charge Calculator</h3></a>
    <div class="slide">
        <form id="batteryForm" action="">
            <p>
                Battery Capacity (mah):
            </p>
            <p>
                <input name="capacity"/>
            </p>
            <p>
                Charge Rate (mA):
            </p>
            <p>
                <input name="rate"/>
            </p>
            <p>
                <input type="submit" value="Submit"/>
            </p>
            <br/>
            <p id="time"/>
        </form>
    </div>
    <a href="#"><h3>Energy Calculator</h3></a>
    <div class="slide">
        <form id="energyForm" action="">
            <p>
                Mass of BB (grammes):
            </p>
            <p>
                <input name="mass"/>
            </p>
            <p>
                Power of weapon (FPS):
            </p>
            <p>
                <input name="velocity"/>
            </p>
            <p>
                <input type="submit" value="Submit"/>
            </p>
            <br/>
            <p id="energy"/>
        </form>
    </div>
</div>

JavaScript

$(function() {
    $('#main > a > h3').click(function() {
        $(this).closest('a').next('div.slide').animate({
            height: 'toggle'
        }, 750);
    });

    function batteryCalc() {
        var capacity = this.capacity.value,
            rate = this.rate.value,
            time = capacity / (rate / 1.2),
            chargeTime = (Math.round(10 * time) / 10).toFixed(1),
            message = 'You must enter values in both fields!';

        if (capacity && rate) {
            message = 'Required time on charge: ' + chargeTime + ' hours';
        }

        $('#time').html(message);
        return false;
    }

    function energyCalc() {
        var mass = this.mass.value,
            finalMass = mass * 1000,
            velocity = this.velocity.value,
            finalVelocity = velocity * 0.3048,
            energy = (0.5 * (finalMass * (finalVelocity * finalVelocity))).toFixed(1),
            message = 'You must enter values in both fields!';

        if (mass && velocity) {
            message = 'Energy of weapon: ' + energy + ' Joules';
        }

        $('#energy').html(message);
        return false;
    }


    $('#batteryForm').submit(batteryCalc);
    $('#energyForm').submit(energyCalc);
});

Demo: http://jsfiddle.net/mattball/JSpaU/

like image 197
Matt Ball Avatar answered Dec 08 '22 14:12

Matt Ball


See the drop-down list on the left that says "onLoad"? Change it to "no wrap (head)" and it'll work.

like image 42
Ry- Avatar answered Dec 08 '22 14:12

Ry-