Click to See Complete Forum and Search --> : Submit when press enter


rbollen
04-30-2003, 09:46 AM
I have a problem.
When I click on button ok, it works

but how can I also make it work when I press the enter key??
is there a method like onEnter or something?

here is the code:

<html>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function checkDecimals(fieldName, fieldValue) {
if (isNaN(fieldValue)) {
alert("Oops! That does not appear to be a valid number. Please try again.");
fieldName.select();
fieldName.focus();
}
if(fieldValue == "") {
alert("Oops! The input box is empty. Please try again.");
fieldName.select();
fieldName.focus();
}
}
</script>
</HEAD>
<BODY>
<center>
<form action="test.html" method="post" >
Please enter a number with up to 2 decimal places: <br>
<input type=text name="aantalbest">
<input type=button name=ok value="Ok" onClick="return checkDecimals(this.form.aantalbest, this.form.aantalbest.value)" >
</form>
</center>
</body>
</html>

Fang
04-30-2003, 10:45 AM
Here's the basic code:

<script language="javascript">
<!--
document.onkeypress = keyhandler;
function keyhandler(e) {
var event = e ? e : window.event;
if (event.keyCode == 13) { alert("Enter Pressed");}
}
// -->
</script>

Charles
04-30-2003, 11:30 AM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Some Title</title>

<SCRIPT LANGUAGE="JavaScript">
function checkDecimals(f) {
if (isNaN(f.aantalbest.value) || !/^\d*(\.\d{0,2})?$/.test(f.aantalbest.value)) {
alert("Oops! That does not appear to be a valid number. Please try again.");
f.aantalbest.value = '';
f.aantalbest.focus();
return false;
}
if(f.aantalbest.value == '') {
alert("Oops! The input box is empty. Please try again.");
f.aantalbest.value = '';
f.aantalbest.focus();
return false;
}
}
</script>
</HEAD>
<BODY>
<center>
<form action="test.html" method="post" onsubmit="return checkDecimals(this)">
Please enter a number with up to 2 decimal places: <br>
<input type=text name="aantalbest">
<input type=submit name=ok value="Ok")" >
</form>
</center>
</body>
</html>

And I've taken the liberty of adding some range checking. This form will reject any number with more than two decimal places.

Jona
04-30-2003, 11:30 AM
In your <form> tag: onsubmit="return checkDecimals(this.form.aantalbest, this.form.aantalbest.value)"

And make your "ok" button <input type=submit>.

Also, in your code, add return false; twice, like this:

function checkDecimals(fieldName, fieldValue) {
if (isNaN(fieldValue)) {
alert("Oops! That does not appear to be a valid number. Please try again.");
fieldName.select();
fieldName.focus();
return false;
}
if(fieldValue == "") {
alert("Oops! The input box is empty. Please try again.");
fieldName.select();
fieldName.focus();
return false;
}
}