Is it possible to set an HTML button as default inside a form?

10,104

Solution 1

Try this :

   // JavaScript Code
   var body = document.getElementsByTagName('body')[0];
    body.onkeydown = function (e) {
        if (e.keyCode === 13) {  //enter key code
         // call your html button onclick code here
        }
    }

Solution 2

I'm using JQuery, so I modified the code in the Mohit Pandey answer:

$("body").keypress(function (event) {
    if (event.which == 13) {
        event.preventDefault();
        // my function
    }
});

Solution 3

read this article http://www.codeproject.com/Articles/35180/How-To-set-Default-Button-for-ENTER-key-pressed-ev

you can use it in somewhat this way

<form id="form1" runat="server" defaultbutton="Button1" >
Share:
10,104
davioooh
Author by

davioooh

Hi, I'm David Castelletti. I like to create things with Java &amp; Kotlin (❤). LinkedIn profile Personal Page + Blog (italian)

Updated on July 04, 2022

Comments

  • davioooh
    davioooh almost 2 years

    I'm working on a asp.net page and I have several buttons in my page, some of them are asp.net buttons, other are HTML input[type=button] elements. HTML buttons are used to make AJAX calls.

    When the user press ENTER I need to set as default button one of these HTML buttons, but at the moment the first button in the page is trigged.

    Is there a way to set a plain HTML button as default on my form?

  • Henk Mollema
    Henk Mollema over 11 years
    If you give the button an ID="btnSomething" and runat="server", it should.