Jump to content

Make enter NOT refresh the page


cpd

Recommended Posts

In a form, how do i make the page NOT refresh when hitting the "Enter" key after typing in a text box

 

<form method="post">

<input type="text" name="message">

</form>

 

say i was focused on that text box how do i make it so that when the form is submitted it doesnt refresh the page?

 

Cheers

Link to comment
https://forums.phpfreaks.com/topic/167043-make-enter-not-refresh-the-page/
Share on other sites

In a form, how do i make the page NOT refresh when hitting the "Enter" key after typing in a text box

 

<form method="post">

<input type="text" name="message">

</form>

 

say i was focused on that text box how do i make it so that when the form is submitted it doesnt refresh the page?

 

Cheers

 

this isn't possible, because submitting the form sends a new request to the server and therefore forces a refresh. what exactly are you trying to achieve?

You should use onkeypress event on your form:

 

onkeypress="isEnter(this, event)

 

then handle event to check is enter pressed:

 

function isEnter(obj, evt)
{	var key= new Number;
if (window.event)
{	key = window.event.keyCode;
}	else if(evt)
{	key = evt.which;
}	else
{	return true;
}
if (key == 13)
{
	return true;
}
}

Just for everybodies benefit ive found a way of doing it thats really easy and simple.

 

function searchKeyPress(e){
if(window.event){
	e = window.event; 
}
if(e.keyCode == 13){
	// Code to execute
}
}

 

then in your input tag that IS NOT wrapped in <form> tags

 

onkeypress="searchKeyPress(event);"

 

Both people who have tried my chat feature were using Firefox and i am using firefox too however it works fine for me. It was on a local server and ive uploaded it to an online server and it works ok, could that of been the problem?

 

Javascript doesn't depends on server.

The way you are checking pressed key is preferred in IE.

I think, but not 100% sure, that onKeyPress should return value to indicate that handled event.

Anyway look at:

 

http://www.w3schools.com/jsref/jsref_onkeypress.asp

 

Or submit it to an iframe. The iframe can be hidden with CSS

 

<iframe name="frame"></iframe>

 

<form method="post" target="frame">

<input type="text" name="message">

</form>

 

Or, if you don't want the form to submit at all:

 

<form method="post" onsubmit="return false;">

<input type="text" name="message">

</form>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.