Reputation: 3351
I've the below code.
<!doctype html>
<html>
<head>
<style type="text/css">
#error
{
color: red;
}
</style>
<script type='text/javascript'>
function showpay() {
if ((document.calc.loan.value == null || document.calc.loan.value.length == 0) ||
(document.calc.months.value == null || document.calc.months.value.length == 0) ||
(document.calc.rate.value == null || document.calc.rate.value.length == 0)) {
document.calc.pay.value = "Incomplete data";
}
else {
var princ = document.calc.loan.value;
var term = document.calc.months.value;
var intr = document.calc.rate.value / 1200;
document.calc.pay.value = princ * intr / (1 - (Math.pow(1 / (1 + intr), term)));
}
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
{
document.getElementById('error').style.display = 'inline';
document.getElementById('error').style.color = 'red';
document.getElementById('error').innerHTML = 'OOPs! Only digits allowed.';
} else {
document.getElementById('error').style.display = 'none';
return true;
}
}
</script>
</head>
<body>
<form name="calc">
<p>
<center>
<table width="200" border="1">
<tbody>
<tr>
<th scope="col">Description</th>
<th scope="col">Data Entry</th>
</tr>
<tr>
<td>Principle</td>
<td><input type="text" name="loan" id="loan" onkeypress="return isNumberKey(event)">
</td><span id="error"/>
</tr>
<tr>
<td>Interest</td>
<td><input type="text" name="rate" id="rate" onkeypress="return isNumberKey(event)">
</td><span id="error"/>
</tr>
<tr>
<td>Tenure</td>
<td>
<input type="text" name="months" id="months" onkeypress="return isNumberKey(event)">
</td><span id="error"/>
</tr>
<tr>
<td>EMI</td>
<td>
<input name="textfield4" type="text" id="pay" readonly></td>
</tr>
<tr>
<td><input type="button" value="Submit" onClick='showpay()'/></td>
<td><input type=reset value=Reset></td>
</tr>
</tbody>
</table>
<font size=1>Enter only numeric values (no commas), using decimal points
where needed.<br>
Non-numeric values will cause errors.</font>
</center>
</p>
</form>
</body>
</html>
here i'm facing 2 problems,
.
should be accepted..
(decimal numbers).please let me know how can i achieve these.
Thanks
Upvotes: 0
Views: 64
Reputation: 16369
This will fix the check of the keypress
, but you need to change the id
of the items so that you do not have multiple error id
s. That is invalid HTML, which is probably why its not working as you expect.
function isNumberKey(e) {
var charCode = (e.which ? e.which : e.keyCode),
valid;
switch(charCode){
case 96:
case 97:
case 98:
case 99:
case 100:
case 101:
case 102:
case 103:
case 104:
case 105:
case 190:
valid = true;
break;
default:
valid = false;
break;
}
if(valid){
// remove the error
} else {
// add the error
}
return valid;
}
This will at least limit the characters you want to accept, as it creates an inclusion list of numeric (0-9) characters plus the period character.
Upvotes: 1