Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to prevent page from reloading when Enter'ing in a text field? 1

Status
Not open for further replies.

rairf

Programmer
Jul 28, 1998
2
0
0
US
I've got a simple page with a text field and a button. When you

type in the name of a color, and press the button, the page's background changes to that color. I've got it set up so that you can also press Tab.



But if you press Enter, the background changes, and then the page reloads.



How can I cause the page to not reload?



Here are the javascript functions in the page's head:



function setColor(color) {

document.bgColor=color;

}



function maybeSetColor(color, e) {

var charCode = (navigator.appName == "Netscape") ? e.which : e.keyCode;

if (charCode == 13) {

setColor(color);

}

return false;

}



And here are the form elements. They're in a table, to make them align nicely:



‹table border="0" width="20%" align="center" cellspacing="0" cellpadding="0"›

‹tr›

‹td align="center"›

‹input type="text" name="colorField"

onBlur="setColor(document.forms[0].colorField.value)"

onKeyPress="maybeSetColor(document.forms[0].colorField.value, event)"›

‹/td›

‹/tr›

‹tr›

‹td align="center"›

‹input type="button" name="setColorButton" value="Set background"

onClick="setColor(document.forms[0].colorField.value)"›

‹/td›

‹/tr›

‹/table›


 
I am new to javascript, but it seems that you are having a problem with explorer's event bubbling. Try turning that off (I'm not sure how). Also, in Netscape Navigator, The 'enter' seems to be including itself in the text field, causing an error. You may have to strip this character off the end of the colorfield string.
 
I bet what's happening is your form is being submitted. Do you have an action specified in the form tag? If so, you might add:<br>

onSubmit="return false;" to the form tag, and that will prevent the reloading.<p>



Another way to do this is to simply add another form to the page with one hidden field. When there are multiple forms on a page, enter will no longer submit a form.
 
Geez, I am reading a post from 1998...thats so cool, I wasn t even in college yet, and probably have no clue what JavaScript is...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top