Brain Flush

Defining default buttons in HTML forms using JavaScript

Posted in Software Development & Programming by Matthias Käppler on December 8, 2007

Being a keyboard junky myself, I recently stumbled over the somewhat annoying fact that it seems to be impossible to explicitly tell a web browser what the default button in an HTML form is, i.e. which button will be activated when the user hits the ENTER key. I suspected some kind of “default” attribute to be set on a button, but nada, there simply is no such thing. The default button of an HTML form is always the “submit” button.

This is pretty useless for AJAX applications, where you typically do not want to submit the form by evaluating the action parameter of the form, but instead want to trigger an asynchronous request that carries the data of the form. The obvious solution is to exploit the action parameter of the surrounding form: Instead of providing a server URL, you simply execute the click-handler of the button you want to be the default button:

<script type="text/javascript">
    function sendForm() {
        alert ("sending data");
    }
</script>
<form id="MyForm" action="javascript:sendForm()">
   <input type="text" size="50" name="myParam"/>
   <input type="button" name="myButton" value="Send"
        onclick="sendForm()"/>
</form>

Whenever the user hits the ENTER key, the button’s click-handler is invoked. Technically, no actual click event is fired of course. But it does the job.

5 Responses

Subscribe to comments with RSS.

  1. GratefulVisitor said, on April 7, 2009 at 7:22 pm

    Many thanks!

    I had the “Enter problem” with my ajax-search-script, and you solve it perfectly with this script :)

    Owe you 1 ;)

  2. Д said, on May 22, 2009 at 9:49 am

    Спасибо. То, что нужно ))

  3. Carl L. said, on June 22, 2009 at 8:05 pm

    Great idea! Just what I wanted.

    Greetings from Canada,
    Carl L.

  4. bulee said, on September 30, 2009 at 7:00 am

    for me working only with one textbox

  5. Syed Abdul Rahim said, on November 4, 2009 at 8:59 am

    Excellent – Worked like a charm


Leave a Reply