[thelist] detecting form fields in JS

jeff jeff at members.evolt.org
Mon Dec 11 19:11:43 CST 2000


matthew,

:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: From: Matthew Walker
:
: Anybody know how to control which submit button
: on a form is the default if somebody just hits enter?
: It seems to be the first one encountered in the
: HTML (in IE anyway).
:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

you can't affect it directly with straight html.  also, no promises you'll
get anything like this to work in nn4/nn6.  just grab the keycode from the
document and call the click() method on the button you want it to default
to.

<script language="JavaScript" type="text/javascript">
<!--
  function keyDown()
  {
    if(event.keyCode == 13)
    {
      document.forms[0].button2.click();
    }
  }

  document.onkeydown = keyDown;
// -->
</script>

however, if you have textareas within your form this method will cause you
some problems as the user will need to use the [enter] key.  when they do
they'll get some odd behavior - namely an error.  so, you'll need to
identify when any textareas receive focus and not perform this function if a
textarea has focus.  the improved function would look like this:

<script language="JavaScript" type="text/javascript">
<!--
  var textareaFocused = false;

  function keyDown()
  {
    if(event.keyCode == 13 && !textareaFocused)
    {
      document.forms[0].button2.click();
    }
  }

  document.onkeydown = keyDown;
// -->
</script>

and then you'd need to include the following in every textarea:

onFocus="textareaFocused = true" onBlur="textareaFocused = false"

again, this code assumes that the only browser using it is ie4+.  nn4/nn6
will puke on it without some modifications.

good luck,

.jeff

name://jeff.howden
game://web.development
http://www.evolt.org/
mailto:jeff at members.evolt.org





More information about the thelist mailing list