Square or Rectangle (Practice Prob.)
Tags : JavaScript Intro
Practice Problem
Please finish this problem before class starts.
Notice how we are separating our logic( squareOrRectangle function) from the user interface ( $("form").on ... ) section of the code. This is very helpful to organize our code.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Square or Rectangle</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
<script src="scripts/jquery-1.11.3.js"></script>
<script src="scripts/myscript.js"></script>
</head>
<body>
<div class="container">
<h1>Square or Rectangle</h1>
<form>
<div class="form-group">
<label>Side A</label>
<input type="text" id="side-a" placeholder="Side A">
</div>
<div class="form-group">
<label>Side B</label>
<input type="text" id="side-b" placeholder="Side B">
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
<h2><span id="result"></span></h2>
</div>
</body>
</html>
myscript.js
$(document).ready(function(){
function squareOrRectangle(sideA, sideB){
if (sideA > 0 && sideB > 0){
if(sideA === sideB){
return "square";
} else {
return "rectangle";
}
} else {
return "invalid input";
}
}
$("form").on("submit", function(event){
event.preventDefault();
var sideA = parseInt($("input#side-a").val());
var sideB = parseInt($("input#side-b").val());
var result = squareOrRectangle(sideA, sideB);
$("span#result").text(sideA + " X " + sideB + " is a " + result);
})
})
Try the following:
- Watch the video and rewrite the solution to this problem. Try not to copy the code verbatim. Analyze what every piece of code is doing.