Can someone please tell me how to submit an HTML form when the return key is pressed and if there are no buttons in the form? The submit button is not there. I am using a custom div instead of that.
Why don't you just apply the div submit styles to a submit button? I'm sure there's a javascript for this but that would be easier.
Here is how I do it with jQuery
j(".textBoxClass").keypress(function(e)
{
// if the key pressed is the enter key
if (e.which == 13)
{
// do work
}
});
Other javascript wouldnt be too different. the catch is checking for keypress argument of "13", which is the enter key
I would definitely not recommend using Sean Chambers or Remiu's method - as that only applies to certain keyboard varieties (mainly Latin-based, Western European and US keyboards) as it uses a keymap value, rather than an 'event' of some description (so, you need a fallback).
The simplest way to do this is to do as Ross said, and apply your DIV styles to a Submit or image button, and achieve your functionality that way.
Use the following script.
<SCRIPT TYPE="text/javascript">
<!--
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}
//-->
</SCRIPT>
For each field that should submit the form when the user hits enter, call the submitenter function as follows.
<FORM ACTION="../cgi-bin/formaction.pl">
name: <INPUT NAME=realname SIZE=15><BR>
password: <INPUT NAME=password TYPE=PASSWORD SIZE=10
onKeyPress="return submitenter(this,event)"><BR>
<INPUT TYPE=SUBMIT VALUE="Submit">
</FORM>
IMO, this is the cleanest answer:
<html>
<head><title>title</title></head>
<body>
<form action="" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password"/><br/>
<div class="yourCustomDiv"/>
<input type="submit" style="display:none"/>
</form>
</body>
</html>
Better yet, if you are using javascript to submit the form using the custom div, you should also use javascript to create it, and to set the display:none style on the button. This way users with javascript disabled will still see the submit button and can click on it.
If you are using asp.net you can use the defaultButton attribute on the form.
I think you should actually have a submit button or a submit image... Do you have a specific reason for using a "submit div"? If you just want custom styles I recommend <input type="image"...
. http://webdesign.about.com/cs/forms/a/aaformsubmit_2.htm