in ASP.NET

handling multiple submit buttons in one form (asp.net webforms)

I came across an issue where I had the following setup with an asp.net website:

  1. I had a master page with one main form element
  2. I had a submit button in the master page which acts as a search button across the website
  3. I had a login page that also has a submit button

Naturally when the user presses the enter key, it naturally takes the first submit button on the webpage as being the default submit button.   Therefore when a user enters their credentials on the login page, they will always be taken to the search page which is defined by the input button on the master page.

I used jQuery to help solve this issue, you need to do two important things:

1) You need to set a default selector on the input button you want to submit, i.e on the login button I put:

1
 <input class="buttondefault" name="myButton" type="submit" />

 

2) Use the following code (Note this code can easily be refactored to be more efficient):

1
2
3
4
5
6
7
8
9
10
11
12
13
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
//if the search has text then submit that button first
if ($('.buttondefault').length > 0) {
$('.buttondefault').click();
return false;
}
$('#myMasterButtonClass input[type=submit]').click();
return false;
} else {
return true;
}
});