Using enter key to submit AJAX Query

Get Help With All Aspects of Web Design & Design Software

Moderators: Moderator, Global Moderator

Post Reply
ner0
Newbie
Newbie
Posts: 0
Joined: Sat May 22, 2004 4:45 pm

Using enter key to submit AJAX Query

Post by ner0 »

Hi all,

busy day for me on here!.. here\'s another problem I had today:
Have coded a pretty nice AJAX enabled form, which basically takes a value entered into a text field, queries a mySQL database, and returns a bunch of data regarding whatever text is entered.

All was fine and dandy up until this point, it was simple enough to shove an \'onclick\' onto a form button (<input type=\"button\" onclick=\"blahblahblah\".... />)

Though what if (and I almost always do this) my user decides to use the enter/return key to submit the form?

The code then decided to use the normal form.submit action, and kept throwing me back to my index page, obviously not as I\'d have hoped.

So I knew I had to somehow override the enter key\'s functionality for this form, but how? Well here goes.

Every time someone presses a key while focussed on the text field, I\'d run a command and check whether that key was \'return\'.. if it was, I\'d execute the relevant AJAX function, halt the default form action, and be done! otherwise I\'d just let the character appear, so my script would be completely transparent.

Here\'s the code for the input field (HTML):

Code: Select all

<input onkeydown=&#092;"return entSub&#40;event,this.form,\'{$nav->script}/e/userCheck\'&#41;;&#092;" type=&#092;"text&#092;" name=&#092;"text&#092;" />
the \'{$nav->script}/e/userCheck\' parameter of the function is the parameter I need to pass to my AJAX function, obviously yours will differ to this.

Now for the j&#097;v&#097;script \'entSub\' code...

Code: Select all

function entSub&#40;event,formName,xmlPostParam&#41; {
// Enter funcion with event &#40;i.e. what happened to make this function execute&#41;.. the form\'s name.. and whatever we\'re passing to xmlhttpPost //
	if &#40;event && event.which == 13&#41;
// if event exists, and is 13 &#40;enter key being pressed&#41;...
	{
// call xmlHttpPost using the parameter submitted...
		xmlhttpPost&#40;xmlPostParam&#41;;
// and DON\'T submit the form using normal methods
		return false;
	}
// if our event is -not- the enter key being pressed..
	else
	{
// display the character entered in the text field..
		return true;
	}
}
As always, probably more elegant ways of accomplishing this, but this code suited my application the most...
enjoy!
Last edited by ner0 on Sat Mar 17, 2007 7:45 pm, edited 1 time in total.
[color=\"green\"]'class KPIM::ProcessManager' only defines private constructors and has no friends[/color] <- :( poor class



[18:09:00] * ~Moppy stews ner0 erotically 1 times.
Post Reply

Return to “Web Design Principles”