Reputation:
I have two inputs width and height to calculate the area of a triangle. When you type number in each input for width and height I then need a submit button to multiply width x height and insert total area into an input.
HTML:
<p id="instructions" class="Main">Enter the width and height of your triangle to calculate the area.</p>
<!--Main div-->
<form id="mainform">
Width (b):
<input type="Text" id="width" placeholder="width" >
<div>
Height(h):
<input type="text" id="height" placeholder="height">
</div>
<button type="button" id="total" onclick="calculateArea()">Calculate Area</button>
</form>
<!--Divider-->
<form>
<div id="divider">
</div>
<div id="area">
The area is:
<input type="text" name="txtarea" id="total">
</div>
</form>
</div>
JavaScript:
function calculateArea() {
var width = document.getElementById('width').value;
var height = document.getElementById('height').value;
var total = document.getElementById('total');
total.value = width * height;
}
Upvotes: 0
Views: 82
Reputation: 23
You can write return myResult
, then the calculateArea function will return myResult.
Also, "id" is used for unique elements - use "class" for multiple elements.
Upvotes: 0
Reputation: 869
id="total"
. Change the id attribute on your button to something else or remove it.myResult
in the last line of your javascript function. Casing matters in javascript.Upvotes: 0
Reputation: 2380
total.value = myResult;
There was a typo error too. function calculateArea() {
var width = document.getElementById('width').value;
var height = document.getElementById('height').value;
var total = document.getElementById('product');
var myResult = width * height;
total.value = myResult;
}
<p id="instructions" class="Main">Enter the width and height of your triangle to calculate the area.</p>
<!--Main div-->
<form id="mainform">
Width (b):
<input type="Text" id="width" placeholder="width">
<div>
Height(h):
<input type="text" id="height" placeholder="height">
</div>
<button type="button" id="total" onclick="calculateArea()">Calculate Area</button>
</form>
<!--Divider-->
<form>
<div id="divider">
</div>
<div id="area">
The area is:
<input type="text" name="txtarea" id="product">
</div>
</form>
</div>
Upvotes: 1
Reputation: 11
You should select the element by Id and then assign the result as value to the element
So in your case, it should be: remove the total as id from the button. Now you have only one element with the unique id 'total' document.getElementById("txtArea").value = result;
Upvotes: 0
Reputation: 1172
You have the wrong element with the id "total". The button shouldn't, the input should.
Upvotes: 0