Brain Flush

December 8, 2007

Defining default buttons in HTML forms using JavaScript

Filed under: Software Development & Programming — Tags: , , , — Matthias @ 1:23 pm

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.

Advertisements

6 Comments »

  1. Many thanks!

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

    Owe you 1 ;)

    Comment by GratefulVisitor — April 7, 2009 @ 7:22 pm

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

    Comment by Д — May 22, 2009 @ 9:49 am

  3. Great idea! Just what I wanted.

    Greetings from Canada,
    Carl L.

    Comment by Carl L. — June 22, 2009 @ 8:05 pm

  4. for me working only with one textbox

    Comment by bulee — September 30, 2009 @ 7:00 am

  5. Excellent – Worked like a charm

    Comment by Syed Abdul Rahim — November 4, 2009 @ 8:59 am

  6. Real effective, thank you.

    Comment by Dinh song — May 8, 2012 @ 2:14 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: