Click to See Complete Forum and Search --> : How to set a default button in form?


George Ma
September 20th, 2002, 08:29 AM
Hi, everyone!

I have several buttons in a form of an html
file. I want to set one of the buttons a default
button, so that when customer press "Enter", the
OnClick method of the button will be called.

How to do it? Can you give me a simple example?

Cheers,
George

Waldo2k2
September 20th, 2002, 04:24 PM
<script language="javascript">
function FireMouse()
{
//sorry, this is all IE specific, but it's a start
//besides DOM syntax, i know that NN uses dispatchEvent(), so that should help
document.all.forms[0].button1.fireEvent("onclick");
}
</script>

<input type="button" id="button1" onKeyUp="FireMouse()">button 1</input>

i'm not exactly sure how this will turn out, i know it's not perfect, but i've given you the start you need i think. If you need anything else let me know (as far as functions go, i'm not going to write the whole thing for you...it's kind of a pain to work with multiple buttons like that). good luck.

websmith99
September 23rd, 2002, 03:53 PM
OK here's some sample code that will detect if the "enter" key was pressed. It works on IE4+, NN4, and NN6. Note that the
user can be anywhere on the page when they press the "enter" key.

Once you know the enter key was pressed, it's a matter of
firing the event as Waldo2k2 pointed out.


<html>
<head>
<script language="JavaScript">
if (document.all) {
} else if (document.layers) {
document.captureEvents(Event.KEYPRESS);
document.onkeydown = getKeyCode;
} else if (document.getElementById) {
document.addEventListener("keyup",getKeyCode,true);
}

function getKeyCode(e) {
keyPressed = 0;
if (document.all) {
keyPressed = event.keyCode;
} else if (document.layers) {
keyPressed = e.which;
} else if (document.getElementById) {
keyPressed = e.keyCode;
}
if (keyPressed == 13) {
// we have detected that the "enter" key was pressed
// here should be the code to fire the onClick event of
// the button
}
}
</script>
</head>
<body onkeydown="getKeyCode()">
<form>
<input type="button" name="foo" onClick="">
</form>
</body>
</html>