Friday, August 21, 2015

calculator using javascript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>calculator</title>
</head>
<body>
Number 1: <input type="text" name="" id="number_one"> <br><br>
Number 2: <input type="text" name="" id="number_two"> <br><br>
operator: <input type="text" name="" id="operator"> <br><br>
<button onclick="calculator()">Click for result</button>
<p>Result:</p>
<div id="result"></div>
<script>
function calculator(){
var number_one = Number(document.getElementById('number_one').value);
var number_two = Number(document.getElementById('number_two').value);
var operator = document.getElementById('operator').value;
var result_div = document.getElementById('result');
var result;
if(isNaN(number_one) || isNaN(number_two)){
result = "You have to enter a valid number";
} else {
if(operator == '+'){
result = number_one + number_two;
} else if(operator == '-'){
result = number_one - number_two;
} else if ( operator == '*' ){
result = number_one * number_two;
} else if (operator == "/"){
if(number_two == 0){
result = "In division second number can't be zero";
} else {
result = number_one / number_two;
}
} else {
result = "Currently our calculator only support + - * /";
}
}
result_div.innerHTML = result;
}
</script>
</body>
</html>

No comments:

Post a Comment

css snippet for blogger code highlighting

code, .code {     display: block;     background: beige;     padding: 10px;     margin: 8px 15px; }