Skip to content

Instantly share code, notes, and snippets.

@gglin
Created July 2, 2013 22:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gglin/5913814 to your computer and use it in GitHub Desktop.
Save gglin/5913814 to your computer and use it in GitHub Desktop.
jQuery Calculator
/* Write the JS necessary to calculate values after a number is changed inside the form field.
Hints:
1.) Learn about change event methods: http://api.jquery.com/change/
2.) Learn about retrieving values from form inputs: http://api.jquery.com/val/
3.) Learn how to select specific inputs using eq selectors: http://api.jquery.com/eq-selector/
*/
$(document).ready(function() {
function calculate(operator, ele) {
var x = $(ele).find("input:eq(0)").val();
var y = $(ele).find("input:eq(1)").val();
var answer = eval(x+operator+"("+y+")");
return answer;
}
function calc(ele, operator) {
$(ele).change(function() {
var answer = calculate(operator, this);
$(this).find("input:eq(2)").val(answer);
});
}
calc('#addition','+');
calc('#subtraction','-');
calc('#multiplication','*');
calc('#division','/');
calc('#modulus','%');
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Calculations</title>
<link rel="stylesheet" href="css/style.css">
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<h1>Calculations</h1>
<div id="addition">
<input type="text"></input> + <input type="text"></input> = <input type="text"></input>
</div>
<div id="subtraction">
<input type="text"></input> - <input type="text"></input> = <input type="text"></input>
</div>
<div id="multiplication">
<input type="text"></input> * <input type="text"></input> = <input type="text"></input>
</div>
<div id="division">
<input type="text"></input> / <input type="text"></input> = <input type="text"></input>
</div>
<div id="modulus">
<input type="text"></input> % <input type="text"></input> = <input type="text"></input>
</div>
</div><!-- #wrapper -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.8.0.min.js"><\/script>')</script>
<script src="js/calc.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment