JSFiddle - React, Tailwind, and code Playground
by thewolff
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Rectangle Calculator</title>
<script src="rectangle.js"></script>
</head>
<body>
<h3>Program Calculates the Area and Perimeter of Rectangles</h3>
<p>Enter the Length <input type="text" id="length" /></p>
<p>Enter the Width <input type="text" id="width" /></p>
<p><input type="button" id="calc" value="Calculate" /></p>
<p id="display"></p>
</body>
</html>
JavaScript
const Rectangle = function(r, x){
this.width = r;
this.length = x;
this.perimeter = function(){
return (this.length + this.width) * 2;
};
this.area = function(){
return (this.length * this.width)
}
};
const updateDisplay = (msg) => {
document.getElementById('display').innerHTML = msg
}
const showData = () => {
const wid = parseFloat(document.getElementById('width').value);
const len = parseFloat(document.getElementById('length').value);
if(isNaN(wid) || wid <= 0 ||isNaN(len) || len <= 0) {
updateDisplay('Please enter numbers only')
return;
}
const myRectangle = new Rectangle(wid, len);
updateDisplay(`Perimeter: ${myRectangle.perimeter()} Area: ${myRectangle.area()}`);
}
document.getElementById('calc').addEventListener('click', showData);