Sorry I'm rather new to coding in JavaScript. I'm trying to make a simple program that takes two inputs, for base and height, and outputs the area of a triangle.
My HTML is this:
<form name="input" action="" method="get">
<label for="">Width (b): </label><input type="textbox" name="width"></input><br>
<label for="">Height (h): </label><input type="textbox" name="height"></input><br>
<button onClick="calculateArea()">Calculate area</button>
</form>
<label for="output">The area is: </label><input type="textbox" name="output"></input>
And my JavaScript is this:
function calculateArea() {
var base = document.getElementById('width').value;
var height = document.getElementById('height').value;
var out = (1/2) * parseFloat(base) * parseFloat(height);
document.output.value = out;
}
I've tried changing the name="output" of the output textbox to an ID and using getValueByID, but it has made no difference. Any help would be appreciated.
You have to get rid of form tag,than change javascript code a little Here is the working example: JSFIDDLE EXAMPLE
HTML:
<label for="">Width (b): </label><input type="textbox" name="width"></input><br>
<label for="">Height (h): </label><input type="textbox" name="height"></input><br>
<button onClick="calculateArea()">Calculate area</button><br>
<label for="output">The area is: </label><input type="textbox" name="output"></input>
JAVASCRIPT:
function calculateArea() {
var base = document.getElementsByName('width')[0].value;
var height = document.getElementsByName('height')[0].value;
var out = (1/2) * parseFloat(base) * parseFloat(height);
document.getElementsByName('output')[0].value= out;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With