Here is a demo page with what you want
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Calculator</title>
<script type="text/javascript">
function trim(str){
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function isNumeric(input){
var regexp = /^[0-9]+$/;
if (regexp.test(input)) {
return true;
}
return false;
}
function calculate(){
var f, s;
f = trim(document.forms['form1'].elements['first'].value);
s = trim(document.forms['form1'].elements['second'].value);
if (f === "" || s === "") {
alert("Any one/All of the textbox contains empty space. Enter a number in both textboxes");
return false;
}
if (isNumeric(f) && isNumeric(s)) {
f = parseInt(f);
s = parseInt(s);
//Commented the validation if the numbers are 0
/*if(f === 0 || s === 0){
alert("Any one/All of the textbox contains 0. Enter a number greater than 0 in both textboxes");
}*/
document.forms['form1'].elements['result'].value = f + s
}else {
alert("Any one/All of the textbox contains non numbers. Enter a number in both textboxes");
}
}
</script>
</head>
<body>
<h1>The Adding Calculator</h1>
<form name="form1">
<label>
Enter Some Numbers in these boxes
</label>
<br>
<br>
<input type="text" name="first" size="20">
<label>
+
</label>
<input type="text" name="second" size="20">
<label>
=
</label>
<input type="text" name="result" size="20">
<br>
<input type="button" value="Calculate" onclick="calculate()">
</form>
</body>
</html>
I have commented the validation if the user enter 0 in any one/all of the textbox and try to calculate. Since 0 is a number in my opinion the calculation should be carried out. If you want to stop the function if any of the number is 0 uncomment the highlighted section in the above code.
It would be better if you avoid the use of eval() in JavaScript if that is possible. If you can do something without using eval() do it that way. In this case you can do what you want without using eval() simply.
Hope this helps.
Bookmarks