Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output JavaScript into a Textbox

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.

like image 981
user3530169 Avatar asked Apr 13 '14 23:04

user3530169


1 Answers

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;

}
like image 138
natchkebiailia Avatar answered Oct 14 '22 21:10

natchkebiailia