Javascript Number Comparator
Enter two numbers, see which one is greater.
by jdhines
HTML
<h1>Surly Number Comparator</h1>
<h3>Which number is greater?</h3>
<div>
<label for="num1">First Number</label>
<input type="text" name="num1" id="num1" value="5" />
</div>
<div>
<label for="num2">Second Number</label>
<input type="text" name="num2" id="num2" value="6" />
</div>
<a id="compareBtn" href="#">Compare</a>
<h3>Result:</h3>
<div id="console-log"></div>
CSS
.console-line {
font-family: monospace;
margin: 2px;
}
JavaScript
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function (text) {
$("#console-log").append($(consoleLine).html(text));
}
};
var counter = 1;
$(function () {
$('#compareBtn').click(function () {
compareNums();
});
});
function greaterNum(num1, num2) {
var result;
if (num1 > num2) {
result = 'The first number, ' + num1 + ', is greater than the other number, ' + num2;
counter = 1;
} else if (num1 < num2) {
result = 'The second number, ' + num2 + ', is greater than the first number, ' + num1;
counter = 1;
} else {
if (counter == 1) {
result = 'You stupid oaf. Those are the same number.';
} else if (counter == 2) {
result = 'Seriously? Are you blind? Those numbers are equivalent!';
} else if (counter == 3) {
result = "That's it, I'm done with you. You can compare your own numbers from now on.";
} else {
result = "Nope, not gonna do it.";
}
if (counter == 4) {
counter = 4;
} else {
counter++;
}
}
return result;
}
function compareNums() {
$('#console-log').html('');
var result;
var num1 = $('#num1').val();
var num2 = $('#num2').val();
if (num1 === '' || num2 === '') {
result = 'Enter a number in both fields.';
} else {
result = greaterNum(num1, num2);
}
console.log(result);
}