Jishnu A P
Jishnu A P

Reputation: 14390

Submit form when Enter is pressed

I have an aspx page with many buttons and i have a search button whose event i want to be triggered when user press enter. How can i do this?

Upvotes: 11

Views: 26149

Answers (4)

Shady Mohamed Sherif
Shady Mohamed Sherif

Reputation: 15759

The best way to make from make actions using enter button and on click of the button without the headache to write js check for each input you have if the user press enter or not is using submit input type.

But you would face the problem that onsubmit wouldn't work with asp.net.

I solved it with very easy way.

if we have such a form

<form method="post" name="setting-form" >
   <input type="text" id="UserName" name="UserName" value="" 
      placeholder="user name" >
   <input type="password" id="Password" name="password" value="" placeholder="password" >
   <div id="remember" class="checkbox">
    <label>remember me</label>
    <asp:CheckBox ID="RememberMe" runat="server" />
   </div>
   <input type="submit" value="login" id="login-btn"/>
</form>

You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.

$(document).ready(function () {
            $("#login-btn").click(function (event) {
                event.preventDefault();
                alert("do what ever you want");
            });
 });

Upvotes: 0

ankur
ankur

Reputation: 4733

$(document).ready(function() {

$("#yourtextbox").keypress(function(e) {
        setEnterValue(e);
    });
});

function setEnterValue( e) {
var key = checkBrowser(e);
if (key == 13) {
 //call your post method
}


function checkBrowser(e) {
if (window.event)
    key = window.event.keyCode;     //IE
else
    key = e.which;     //firefox
return key;}

call the above function and it will help you in detecting the enter key and than call your post method.

Upvotes: 0

Oded
Oded

Reputation: 499392

Make it the default button of the form or panel.

Either one has a DefaultButton property that you can set to the wanted button.

Upvotes: 6

m.edmondson
m.edmondson

Reputation: 30922

You set the forms default button:

<form id="Form1"
    defaultbutton="SubmitButton"
    runat="server">

Upvotes: 20

Related Questions